diff --git a/bin/configs/python-experimental.yaml b/bin/configs/python-experimental.yaml new file mode 100644 index 000000000000..1a8ea6e002c2 --- /dev/null +++ b/bin/configs/python-experimental.yaml @@ -0,0 +1,8 @@ +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 +templatingEngineName: handlebars +additionalProperties: + packageName: petstore_api + recursionLimit: "1234" diff --git a/docs/generators.md b/docs/generators.md index 6ce82ffadbbd..2d8876879115 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -54,6 +54,7 @@ The following generators are available: * [php-dt (beta)](generators/php-dt.md) * [powershell (beta)](generators/powershell.md) * [python (experimental)](generators/python.md) +* [python-experimental (experimental)](generators/python-experimental.md) * [python-legacy](generators/python-legacy.md) * [r](generators/r.md) * [ruby](generators/ruby.md) diff --git a/docs/generators/python-experimental.md b/docs/generators/python-experimental.md new file mode 100644 index 000000000000..e61a03a4e606 --- /dev/null +++ b/docs/generators/python-experimental.md @@ -0,0 +1,221 @@ +--- +title: Config Options for python-experimental +sidebar_label: python-experimental +--- + +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: 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| +|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 | +| ---------- | --------------- | +|map|dict| + + +## 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 +|Array|✓|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 + +### 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/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java index 39e7f784cc94..91c8870774a7 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 @@ -1051,6 +1051,9 @@ public void setEmptyVars(boolean emptyVars) { this.emptyVars = emptyVars; } + public boolean getHasItems() { + return this.items != null; + } /** * Remove duplicated properties in all variable list */ 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 c7a22915dbff..7c2430f47149 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 @@ -778,6 +778,10 @@ public void setHasDiscriminatorWithNonEmptyMapping(boolean hasDiscriminatorWithN this.hasDiscriminatorWithNonEmptyMapping = hasDiscriminatorWithNonEmptyMapping; } + public boolean getHasItems() { + return this.items != null; + } + @Override public boolean getIsString() { return isString; } 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 8a96688f5fac..1af3ddbba392 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 @@ -2731,7 +2731,6 @@ public CodegenModel fromModel(String name, Schema schema) { 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; @@ -2823,6 +2822,7 @@ public int compare(CodegenProperty one, CodegenProperty another) { postProcessModelProperty(m, prop); } } + return m; } @@ -2870,16 +2870,15 @@ protected void setAddProps(Schema schema, IJsonSchemaValidationProperties proper } } - - /** - * Recursively look in Schema sc for the discriminator discPropName - * and return a CodegenProperty with the dataType and required params set - * the returned CodegenProperty may not be required and it may not be of type string - * - * @param composedSchemaName The name of the sc Schema - * @param sc The Schema that may contain the discriminator - * @param discPropName The String that is the discriminator propertyName in the schema - */ + /** + * Recursively look in Schema sc for the discriminator discPropName + * and return a CodegenProperty with the dataType and required params set + * the returned CodegenProperty may not be required and it may not be of type string + * + * @param composedSchemaName The name of the sc Schema + * @param sc The Schema that may contain the discriminator + * @param discPropName The String that is the discriminator propertyName in the schema + */ private CodegenProperty discriminatorFound(String composedSchemaName, Schema sc, String discPropName, OpenAPI openAPI) { Schema refSchema = ModelUtils.getReferencedSchema(openAPI, sc); if (refSchema.getProperties() != null && refSchema.getProperties().get(discPropName) != null) { @@ -5199,7 +5198,7 @@ protected void addVars(CodegenModel m, Map properties, List vars, Map properties, Set mandatory) { + protected void addVars(IJsonSchemaValidationProperties m, List vars, Map properties, Set mandatory) { if (properties == null) { return; } @@ -6826,7 +6825,7 @@ public CodegenParameter fromRequestBody(RequestBody body, Set imports, S return codegenParameter; } - private void addVarsRequiredVarsAdditionalProps(Schema schema, IJsonSchemaValidationProperties property){ + protected void addVarsRequiredVarsAdditionalProps(Schema schema, IJsonSchemaValidationProperties property){ setAddProps(schema, property); if (!"object".equals(schema.getType())) { return; 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 815342dfea74..8e3d27c6cd9c 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 @@ -41,6 +41,7 @@ import org.openapitools.codegen.api.TemplateFileType; import org.openapitools.codegen.ignore.CodegenIgnoreProcessor; 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.serializer.SerializerUtils; @@ -527,7 +528,7 @@ void generateModels(List files, List allModels, List unuse Map modelTemplate = (Map) modelList.get(0); if (modelTemplate != null && modelTemplate.containsKey("model")) { CodegenModel m = (CodegenModel) modelTemplate.get("model"); - if (m.isAlias && !(config instanceof PythonClientCodegen)) { + if (m.isAlias && !((config instanceof PythonClientCodegen) || (config instanceof PythonExperimentalClientCodegen))) { // 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 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 new file mode 100644 index 000000000000..187ae357e022 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonExperimentalClientCodegen.java @@ -0,0 +1,2078 @@ +/* + * 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 io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.servers.Server; +import io.swagger.v3.oas.models.tags.Tag; +import org.openapitools.codegen.api.TemplatePathLocator; +import org.openapitools.codegen.ignore.CodegenIgnoreProcessor; +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"; + + protected String packageUrl; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + protected boolean useNose = Boolean.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(); + + modifyFeatureSet(features -> features + .includeSchemaSupportFeatures( + SchemaSupportFeature.Simple, + SchemaSupportFeature.Composite, + SchemaSupportFeature.Polymorphism, + SchemaSupportFeature.Union + ) + .includeDocumentationFeatures(DocumentationFeature.Readme) + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.Custom)) + .securityFeatures(EnumSet.of( + SecurityFeature.BasicAuth, + SecurityFeature.BearerToken, + SecurityFeature.ApiKey, + SecurityFeature.OAuth2_Implicit + )) + .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.")); + + supportedLibraries.put("urllib3", "urllib3-based client"); + supportedLibraries.put("asyncio", "Asyncio-based client (python 3.5+)"); + supportedLibraries.put("tornado", "tornado-based client"); + CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "library template (sub-template) to use: asyncio, tornado, 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"); + + 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)); + } + + // 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(Map objs) { + if (!(Boolean) additionalProperties.get(CodegenConstants.GENERATE_APIS)) { + return; + } + HashMap operations = (HashMap) objs.get("operations"); + ArrayList codegenOperations = (ArrayList) operations.get("operation"); + 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); + try { + File written = processTemplateToFile(operationMap, templateName, filename, true, CodegenConstants.APIS); + } catch (IOException e) { + LOGGER.error("Error when writing template 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 (schema instanceof ComposedSchema && supportsAdditionalPropertiesWithComposedSchema) { + // if schema has properties outside of allOf/oneOf/anyOf also add them + ComposedSchema cs = (ComposedSchema) schema; + if (schema.getProperties() != null && !schema.getProperties().isEmpty()) { + 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(newLine, + "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) where paload 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", + "- 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 usedImportMappings) { + 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 (usedImportMappings.containsKey(simpleRef)) { + LOGGER.debug("Schema unaliasing of {} omitted because aliased class is to be mapped to {}", simpleRef, usedImportMappings.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())), + usedImportMappings); + } + } 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())), + usedImportMappings); + } + } + } 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())), + usedImportMappings); + } + } 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())), usedImportMappings); + } + } + 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 "isoparse('" + 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.toString()); + dateTime = ((Date) dateTimeValue).toInstant().atOffset(ZoneOffset.UTC); + } + strValue = dateTime.format(iso8601DateTime); + } else { + strValue = dateTimeValue.toString(); + } + return "isoparse('" + 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 Map postProcessOperationsWithModels(Map 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' + + HashMap val = (HashMap) objs.get("operations"); + ArrayList operations = (ArrayList) val.get("operation"); + ArrayList> imports = (ArrayList>) objs.get("imports"); + 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 + * + * @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); + + Map allDefinitions = ModelUtils.getSchemas(this.openAPI); + for (String schemaName : allDefinitions.keySet()) { + Schema refSchema = new Schema().$ref("#/components/schemas/" + schemaName); + Schema unaliasedSchema = unaliasSchema(refSchema, importMapping); + String modelName = toModelName(schemaName); + if (unaliasedSchema.get$ref() == null) { + continue; + } else { + HashMap objModel = (HashMap) objs.get(modelName); + if (objModel != null) { // to avoid form parameter's models that are not generated (skipFormModel=true) + List> models = (List>) objModel.get("models"); + for (Map model : models) { + CodegenModel cm = (CodegenModel) model.get("model"); + String[] importModelNames = cm.imports.toArray(new String[0]); + cm.imports.clear(); + for (String importModelName : importModelNames) { + cm.imports.add(toModelImport(importModelName)); + } + } + } + } + } + + return objs; + } + + public CodegenParameter fromParameter(Parameter parameter, Set imports) { + CodegenParameter cp = super.fromParameter(parameter, imports); + 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) { + CodegenProperty cp = super.fromProperty(name, p); + 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; + } else { + cp.nameInSnakeCase = null; + } + if (cp.isEnum) { + updateCodegenPropertyEnum(cp); + } + Schema unaliasedSchema = unaliasSchema(p, importMapping); + 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, importMapping); + CodegenProperty unaliasedProp = fromProperty("body", unaliasedSchema); + 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, importMapping); + 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 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)) { + return value.substring(0, 1).toUpperCase(Locale.ROOT) + value.substring(1); + } else { + return ensureQuotes(value); + } + } + + @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); + } + + /** + * 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.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, importMapping); + 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, importMapping); + if (unaliasedSchema.get$ref() != null) { + String modelName = toModelName(ModelUtils.getSimpleRef(p.get$ref())); + if (referencedModelNames != null) { + referencedModelNames.add(modelName); + } + return prefix + modelName + fullSuffix; + } + } + if (isAnyTypeSchema(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 (isFreeFormObject(p) && getAdditionalProperties(p) == null) { + return prefix + "bool, date, datetime, dict, float, int, list, str" + fullSuffix; + } else if (ModelUtils.isNumberSchema(p)) { + return prefix + "int, float" + 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 documentaion 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) { + 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 + "\""; + } + + public String toExampleValue(Schema schema, Object objExample) { + String modelName = getModelName(schema); + return toExampleValueRecursive(modelName, schema, objExample, 1, "", 0); + } + + 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 + * @return the string example + */ + private String toExampleValueRecursive(String modelName, Schema schema, Object objExample, int indentationLevel, String prefix, Integer exampleLine) { + 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); + } else if (ModelUtils.isNullType(schema) || isAnyTypeSchema(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(); + RgxGen rgxGen = new RgxGen(pattern); + // this seed makes it so if we have [a-z] we pick a + Random random = new Random(18); + String sample = rgxGen.generate(random); + // omit leading / and trailing /, omit trailing /i + Pattern valueExtractor = Pattern.compile("^/?(.+?)/?.?$"); + Matcher m = valueExtractor.matcher(sample); + if (m.find()) { + example = m.group(m.groupCount()); + } else { + example = ""; + } + } 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(); + } + ArraySchema arrayschema = (ArraySchema) schema; + Schema itemSchema = arrayschema.getItems(); + String itemModelName = getModelName(itemSchema); + example = fullPrefix + "[" + "\n" + toExampleValueRecursive(itemModelName, itemSchema, objExample, indentationLevel + 1, "", exampleLine + 1) + ",\n" + closingIndentation + "]" + closeChars; + return example; + } else if (ModelUtils.isMapSchema(schema)) { + if (modelName == null) { + fullPrefix += "dict("; + 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); + example = fullPrefix + "\n" + toExampleValueRecursive(addPropsModelName, addPropsSchema, addPropsExample, indentationLevel + 1, addPropPrefix, exampleLine + 1) + ",\n" + closingIndentation + closeChars; + } else { + example = fullPrefix + closeChars; + } + return example; + } else if (ModelUtils.isObjectSchema(schema)) { + if (modelName == null) { + fullPrefix += "dict("; + 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; + } + } + return exampleForObjectModel(schema, fullPrefix, closeChars, null, indentationLevel, exampleLine, closingIndentation); + } 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); + return exampleForObjectModel(modelSchema, fullPrefix, closeChars, cp, indentationLevel, exampleLine, closingIndentation); + } else { + return fullPrefix + closeChars; + } + } + return fullPrefix + closeChars; + } else { + 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) { + 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); + } + example += toExampleValueRecursive(propModelName, propSchema, propExample, indentationLevel + 1, propName + "=", exampleLine + 1) + ",\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; + // pass in the hashCode as the name to ensure that the returned property is not from the cache + // if we need to set indent on every one, then they need to be different + addPropProp = fromProperty(String.valueOf(property.hashCode()), new Schema()); + addPropProp.name = ""; + addPropProp.baseName = ""; + addPropProp.nameInSnakeCase = null; + additionalPropertiesIsAnyType = true; + } + } else if (schema.getAdditionalProperties() instanceof Boolean) { + if (Boolean.TRUE.equals(schema.getAdditionalProperties())) { + isAdditionalPropertiesTrue = true; + addPropProp = fromProperty(String.valueOf(property.hashCode()), new Schema()); + addPropProp.name = ""; + addPropProp.baseName = ""; + addPropProp.nameInSnakeCase = null; + additionalPropertiesIsAnyType = true; + } + } else { + addPropProp = fromProperty(String.valueOf(property.hashCode()), (Schema) schema.getAdditionalProperties()); + addPropProp.name = ""; + addPropProp.baseName = ""; + 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.isUuid = 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); // for backward compatibility with 2.x + property.isDate = true; + } else if (ModelUtils.isDateTimeSchema(p)) { // date-time format + property.setIsString(false); // for backward compatibility with 2.x + property.isDateTime = true; + } else if (ModelUtils.isDecimalSchema(p)) { // type: string, format: number + property.isDecimal = true; + property.setIsString(false); + } + 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 Map postProcessModels(Map 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; + } +} 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 727ec5d990f3..c353b2a28464 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 @@ -102,6 +102,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.PythonFlaskConnexionServerCodegen org.openapitools.codegen.languages.PythonAiohttpConnexionServerCodegen org.openapitools.codegen.languages.PythonBluePlanetServerCodegen diff --git a/modules/openapi-generator/src/main/resources/python-experimental/README.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/README.handlebars new file mode 100644 index 000000000000..e03e96972ab3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/README.handlebars @@ -0,0 +1,57 @@ +# {{{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 >= 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://{{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-experimental/README_common.handlebars new file mode 100644 index 000000000000..17663663d7c1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/README_common.handlebars @@ -0,0 +1,111 @@ +```python +{{#with apiInfo}}{{#each apis}}{{#unless hasMore}}{{#if hasHttpSignatureMethods}}import datetime{{/if}}{{/unless}}{{/each}}{{/with}} +import time +import {{{packageName}}} +from pprint import pprint +{{#with apiInfo}} +{{#each apis}} +{{#if @first}} +from {{packageName}}.{{apiPackage}} import {{classVarName}} +{{#each imports}} +{{{import}}} +{{/each}} +{{#with operations}} +{{#each operation}} +{{#if @first}} +{{> doc_auth_partial}} + +# Enter a context with an instance of the API client +with {{{packageName}}}.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = {{classVarName}}.{{{classname}}}(api_client) + {{#each allParams}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{#unless required}} (optional){{/unless}}{{#if defaultValue}} (default to {{{.}}}){{/if}} + {{/each}} + + try: + {{#if summary}} # {{{summary}}} + {{/if}} {{#if returnType}}api_response = {{/if}}api_instance.{{{operationId}}}({{#each allParams}}{{#if required}}{{paramName}}{{/if}}{{#unless required}}{{paramName}}={{paramName}}{{/unless}}{{#if hasMore}}, {{/if}}{{/each}}){{#if returnType}} + pprint(api_response){{/if}} + except {{{packageName}}}.ApiException as e: + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) +{{/if}} +{{/each}} +{{/with}} +{{/if}} +{{/each}} +{{/with}} +``` + +## Documentation for API Endpoints + +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}} +{{/each}}{{/with}}{{/each}}{{/with}} + +## Documentation For Models + +{{#each models}}{{#with model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/with}}{{/each}} + +## Documentation For Authorization + +{{#unless authMethods}} + All endpoints do not require authorization. +{{/unless}} +{{#each authMethods}} +{{#if @last}} Authentication schemes defined for the API:{{/if}} +## {{{name}}} + +{{#if isApiKey}} +- **Type**: API key +- **API key parameter name**: {{{keyParamName}}} +- **Location**: {{#if isKeyInQuery}}URL query string{{/if}}{{#if isKeyInHeader}}HTTP header{{/if}} +{{/if}} +{{#if isBasic}} +{{#if isBasicBasic}} +- **Type**: HTTP basic authentication +{{/if}} +{{#if isBasicBearer}} +- **Type**: Bearer authentication{{#if bearerFormat}} ({{{bearerFormat}}}){{/if}} +{{/if}} +{{#if isHttpSignature}} +- **Type**: HTTP signature authentication +{{/if}} +{{/if}} +{{#if isOAuth}} +- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{#unless scopes}}N/A{{/unless}} +{{#each scopes}} - **{{{scope}}}**: {{{description}}} +{{/each}} +{{/if}} + +{{/each}} + +## Author + +{{#with apiInfo}}{{#each apis}}{{#unless hasMore}}{{infoEmail}} +{{/unless}}{{/each}}{{/with}} + +## Notes for Large OpenAPI documents +If the OpenAPI document is large, imports in {{{packageName}}}.apis and {{{packageName}}}.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 {{{packageName}}}.{{apiPackage}}.default_api import DefaultApi` +- `from {{{packageName}}}.{{modelPackage}}.pet import Pet` + +Solution 1: +Before importing the package, adjust the maximum recursion limit as shown below: +``` +import sys +sys.setrecursionlimit(1500) +import {{{packageName}}} +from {{{packageName}}}.apis import * +from {{{packageName}}}.models import * +``` diff --git a/modules/openapi-generator/src/main/resources/python-experimental/README_onlypackage.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/README_onlypackage.handlebars new file mode 100644 index 000000000000..f9fda7de212a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/README_onlypackage.handlebars @@ -0,0 +1,43 @@ +# {{{projectName}}} +{{#if appDescription}} +{{{appDescription}}} +{{/if}} + +The `{{packageName}}` 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 >= 3.6 + +## Installation & Usage + +This python library package is generated without supporting files like setup.py or requirements files + +To be able to use it, you will need these dependencies in your own package that uses this library: + +* urllib3 >= 1.15 +* certifi +* python-dateutil +{{#if asyncio}} +* aiohttp +{{/if}} +{{#if tornado}} +* tornado>=4.2,<5 +{{/if}} + +## Getting Started + +In your own code, to use this library to connect and interact with {{{projectName}}}, +you can run the following: + +{{> README_common }} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/__init__.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/__init__.handlebars new file mode 100644 index 000000000000..e69de29bb2d1 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 new file mode 100644 index 000000000000..1e059f73613a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/__init__api.handlebars @@ -0,0 +1,9 @@ +{{#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__apis.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/__init__apis.handlebars new file mode 100644 index 000000000000..c8466369da77 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/__init__apis.handlebars @@ -0,0 +1,24 @@ +{{#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}}.{{classVarName}} 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}}.{{classVarName}} import {{classname}} +{{/each}} +{{/with}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/__init__model.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/__init__model.handlebars new file mode 100644 index 000000000000..b6b698b04528 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/__init__model.handlebars @@ -0,0 +1,5 @@ +# we can not import model classes here because that would create a circular +# reference which would not work in python2 +# do not import all models into this module because that uses a lot of memory and stack frames +# if you need the ability to import all models from one package, import them with +# from {{packageName}}.models import ModelA, ModelB diff --git a/modules/openapi-generator/src/main/resources/python-experimental/__init__models.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/__init__models.handlebars new file mode 100644 index 000000000000..31eac9cd5440 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/__init__models.handlebars @@ -0,0 +1,18 @@ +# 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 {{packageName}}.{{modelPackage}}.pet import Pet +# or import this package, but before doing it, use: +# import sys +# sys.setrecursionlimit(n) + +{{#each models}} +{{#with model}} +from {{packageName}}.{{modelPackage}}.{{classFilename}} import {{classname}} +{{/with}} +{{/each}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/__init__package.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/__init__package.handlebars new file mode 100644 index 000000000000..26350c7252d3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/__init__package.handlebars @@ -0,0 +1,28 @@ +# coding: utf-8 + +# flake8: noqa + +{{>partial_header}} + +__version__ = "{{packageVersion}}" + +# import ApiClient +from {{packageName}}.api_client import ApiClient + +# import Configuration +from {{packageName}}.configuration import Configuration +{{#if hasHttpSignatureMethods}} +from {{packageName}}.signing import HttpSigningConfiguration +{{/if}} + +# import exceptions +from {{packageName}}.exceptions import OpenApiException +from {{packageName}}.exceptions import ApiAttributeError +from {{packageName}}.exceptions import ApiTypeError +from {{packageName}}.exceptions import ApiValueError +from {{packageName}}.exceptions import ApiKeyError +from {{packageName}}.exceptions import ApiException +{{#if recursionLimit}} + +__import__('sys').setrecursionlimit({{recursionLimit}}) +{{/if}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/api.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/api.handlebars new file mode 100644 index 000000000000..c6c0b423707f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/api.handlebars @@ -0,0 +1,26 @@ +# 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_client.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/api_client.handlebars new file mode 100644 index 000000000000..47c28bff18d0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/api_client.handlebars @@ -0,0 +1,1380 @@ +# coding: utf-8 +{{>partial_header}} + +from dataclasses import dataclass +from decimal import Decimal +import enum +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 + +{{#if tornado}} +import tornado.gen +{{/if}} + +from {{packageName}} import rest +from {{packageName}}.configuration import Configuration +from {{packageName}}.exceptions import ApiTypeError, ApiValueError +from {{packageName}}.schemas import ( + Decimal, + NoneClass, + BoolClass, + Schema, + FileIO, + BinarySchema, + InstantiationMetadata, + 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, int, float)): + # instances based on primitive classes + return 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 ParameterSerializerBase: + @staticmethod + def __serialize_number( + in_data: typing.Union[int, float], name: str, prefix='' + ) -> typing.Tuple[typing.Tuple[str, str]]: + return tuple([(name, prefix + str(in_data))]) + + @staticmethod + def __serialize_str( + in_data: str, name: str, prefix='' + ) -> typing.Tuple[typing.Tuple[str, str]]: + return tuple([(name, prefix + quote(in_data))]) + + @staticmethod + def __serialize_bool(in_data: bool, name: str, prefix='') -> typing.Tuple[typing.Tuple[str, str]]: + if in_data: + return tuple([(name, prefix + 'true')]) + return tuple([(name, prefix + 'false')]) + + @staticmethod + def __urlencode(in_data: typing.Any) -> str: + return quote(str(in_data)) + + def __serialize_list( + self, + in_data: typing.List[typing.Any], + style: ParameterStyle, + name: str, + explode: bool, + empty_val: typing.Union[typing.Tuple[str, str], typing.Tuple] = tuple(), + prefix: str = '', + separator: str = ',', + ) -> typing.Tuple[typing.Union[typing.Tuple[str, str], typing.Tuple], ...]: + if not in_data: + return empty_val + if explode and style in { + ParameterStyle.FORM, + ParameterStyle.MATRIX, + ParameterStyle.SPACE_DELIMITED, + ParameterStyle.PIPE_DELIMITED + }: + if style is ParameterStyle.FORM: + return tuple((name, prefix + self.__urlencode(val)) for val in in_data) + else: + joined_vals = prefix + separator.join(name + '=' + self.__urlencode(val) for val in in_data) + else: + joined_vals = prefix + separator.join(map(self.__urlencode, in_data)) + return tuple([(name, joined_vals)]) + + def __form_item_representation(self, in_data: typing.Any) -> typing.Optional[str]: + if isinstance(in_data, none_type): + return None + elif isinstance(in_data, list): + if not in_data: + return None + raise ApiValueError('Unable to generate a form representation of {}'.format(in_data)) + elif isinstance(in_data, dict): + if not in_data: + return None + raise ApiValueError('Unable to generate a form representation of {}'.format(in_data)) + elif isinstance(in_data, (bool, bytes)): + raise ApiValueError('Unable to generate a form representation of {}'.format(in_data)) + # str, float, int + return self.__urlencode(in_data) + + def __serialize_dict( + self, + in_data: typing.Dict[str, typing.Any], + style: ParameterStyle, + name: str, + explode: bool, + empty_val: typing.Union[typing.Tuple[str, str], typing.Tuple] = tuple(), + prefix: str = '', + separator: str = ',', + ) -> typing.Tuple[typing.Tuple[str, str]]: + if not in_data: + return empty_val + if all(val is None for val in in_data.values()): + return empty_val + + form_items = {} + if style is ParameterStyle.FORM: + for key, val in in_data.items(): + new_val = self.__form_item_representation(val) + if new_val is None: + continue + form_items[key] = new_val + + if explode: + if style is ParameterStyle.FORM: + return tuple((key, prefix + val) for key, val in form_items.items()) + elif style in { + ParameterStyle.SIMPLE, + ParameterStyle.LABEL, + ParameterStyle.MATRIX, + ParameterStyle.SPACE_DELIMITED, + ParameterStyle.PIPE_DELIMITED + }: + joined_vals = prefix + separator.join(key + '=' + self.__urlencode(val) for key, val in in_data.items()) + else: + raise ApiValueError(f'Invalid style {style} for dict serialization with explode=True') + elif style is ParameterStyle.FORM: + joined_vals = prefix + separator.join(key + separator + val for key, val in form_items.items()) + else: + joined_vals = prefix + separator.join( + key + separator + self.__urlencode(val) for key, val in in_data.items()) + return tuple([(name, joined_vals)]) + + def _serialize_x( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + style: ParameterStyle, + name: str, + explode: bool, + empty_val: typing.Union[typing.Tuple[str, str], typing.Tuple] = (), + prefix: str = '', + separator: str = ',', + ) -> typing.Tuple[typing.Tuple[str, str], ...]: + if isinstance(in_data, none_type): + return empty_val + elif isinstance(in_data, bool): + # must be before int check + return self.__serialize_bool(in_data, name=name, prefix=prefix) + elif isinstance(in_data, (int, float)): + return self.__serialize_number(in_data, name=name, prefix=prefix) + elif isinstance(in_data, str): + return self.__serialize_str(in_data, name=name, prefix=prefix) + elif isinstance(in_data, list): + return self.__serialize_list( + in_data, + style=style, + name=name, + explode=explode, + empty_val=empty_val, + prefix=prefix, + separator=separator + ) + elif isinstance(in_data, dict): + return self.__serialize_dict( + in_data, + style=style, + name=name, + explode=explode, + empty_val=empty_val, + prefix=prefix, + separator=separator + ) + + +class StyleFormSerializer(ParameterSerializerBase): + + def _serialize_form( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + name: str, + explode: bool, + ) -> typing.Tuple[typing.Tuple[str, str], ...]: + return self._serialize_x(in_data, style=ParameterStyle.FORM, name=name, explode=explode) + + +class StyleSimpleSerializer(ParameterSerializerBase): + + def _serialize_simple_tuple( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + name: str, + explode: bool, + in_type: ParameterInType, + ) -> typing.Tuple[typing.Tuple[str, str], ...]: + if in_type is ParameterInType.HEADER: + empty_val = () + else: + empty_val = ((name, ''),) + return self._serialize_x(in_data, style=ParameterStyle.SIMPLE, name=name, explode=explode, empty_val=empty_val) + + +@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] + ) -> typing.Tuple[typing.Tuple[str, str]]: + return tuple([(self.name, 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]: + empty_val = ((self.name, ''),) + prefix = '.' + separator = '.' + return self._remove_empty_and_cast( + self._serialize_x( + in_data, + style=ParameterStyle.LABEL, + name=self.name, + explode=self.explode, + empty_val=empty_val, + prefix=prefix, + separator=separator + ) + ) + + def __serialize_matrix( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list] + ) -> typing.Dict[str, str]: + separator = ',' + if in_data == '': + prefix = ';' + self.name + elif isinstance(in_data, (dict, list)) and self.explode: + prefix = ';' + separator = ';' + else: + prefix = ';' + self.name + '=' + empty_val = ((self.name, ''),) + return self._remove_empty_and_cast( + self._serialize_x( + in_data, + style=ParameterStyle.MATRIX, + name=self.name, + explode=self.explode, + prefix=prefix, + empty_val=empty_val, + separator=separator + ) + ) + + def _serialize_simple( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + ) -> typing.Dict[str, str]: + tuple_data = self._serialize_simple_tuple(in_data, self.name, self.explode, self.in_type) + return self._remove_empty_and_cast(tuple_data) + + 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: + tuple_data = self._serialize_json(cast_in_data) + return self._remove_empty_and_cast(tuple_data) + 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: 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.QUERY, + required=required, + style=style, + explode=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] + ) -> typing.Tuple[typing.Tuple[str, str], ...]: + separator = '%20' + empty_val = () + return self._serialize_x( + in_data, + style=ParameterStyle.SPACE_DELIMITED, + name=self.name, + explode=self.explode, + separator=separator, + empty_val=empty_val + ) + + def __serialize_pipe_delimited( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list] + ) -> typing.Tuple[typing.Tuple[str, str], ...]: + separator = '|' + empty_val = () + return self._serialize_x( + in_data, + style=ParameterStyle.PIPE_DELIMITED, + name=self.name, + explode=self.explode, + separator=separator, + empty_val=empty_val + ) + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict] + ) -> typing.Tuple[typing.Tuple[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, explode=self.explode, name=self.name) + elif self.style is ParameterStyle.SPACE_DELIMITED: + return self.__serialize_space_delimited(cast_in_data) + elif self.style is ParameterStyle.PIPE_DELIMITED: + return self.__serialize_pipe_delimited(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: + return self._serialize_json(cast_in_data) + 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: 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.COOKIE, + required=required, + style=style, + explode=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.Tuple[typing.Tuple[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: + return self._serialize_form(cast_in_data, explode=self.explode, name=self.name) + # 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: + return self._serialize_json(cast_in_data) + 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], + ) -> HTTPHeaderDict[str, str]: + tuple_data = self._serialize_simple_tuple(in_data, self.name, self.explode, self.in_type) + return self.__to_headers(tuple_data) + + 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: + return self._serialize_simple(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: + tuple_data = self._serialize_json(cast_in_data) + return self.__to_headers(tuple_data) + 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 + + +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. + """ + + def __init__( + self, + schema: typing.Type[Schema], + encoding: typing.Optional[typing.Dict[str, Encoding]] = None, + ): + self.schema = schema + self.encoding = encoding + + +@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 OpenApiResponse: + 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: + decoded_data = response.data.decode("utf-8") + return json.loads(decoded_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 + + def deserialize(self, response: urllib3.HTTPResponse, configuration: Configuration) -> ApiResponse: + content_type = response.getheader('content-type') + deserialized_body = unset + streamed = response.supports_chunked_reads() + if self.content is not None: + if content_type == 'application/json': + body_data = self.__deserialize_json(response) + elif content_type == 'application/octet-stream': + body_data = self.__deserialize_application_octet_stream(response) + else: + raise NotImplementedError('Deserialization of {} has not yet been implemented'.format(content_type)) + body_schema = self.content[content_type].schema + _instantiation_metadata = InstantiationMetadata(from_server=True, configuration=configuration) + deserialized_body = body_schema._from_openapi_data( + body_data, _instantiation_metadata=_instantiation_metadata) + elif streamed: + response.release_conn() + + deserialized_headers = unset + if self.headers is not None: + deserialized_headers = unset + + 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 = '{{#if httpUserAgent}}{{{httpUserAgent}}}{{/if}}{{#unless httpUserAgent}}OpenAPI-Generator/{{{packageVersion}}}/python{{/unless}}' + + 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 + + {{#if tornado}} + @tornado.gen.coroutine + {{/if}} + {{#if asyncio}}async {{/if}}def __call_api( + self, + resource_path: str, + method: str, + path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + query_params: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = 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, + 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 + + # path parameters + if path_params: + for k, v in path_params.items(): + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=self.configuration.safe_chars_for_path_param) + ) + + # auth setting + self.update_params_for_auth(headers, query_params, + 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 = {{#if asyncio}}await {{/if}}{{#if tornado}}yield {{/if}}self.request( + method, + url, + query_params=query_params, + headers=headers, + fields=fields, + body=body, + stream=stream, + timeout=timeout, + ) + 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.Tuple[typing.Tuple[str, str], ...]] = 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, + 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 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, + path_params, + query_params, + headers, + body, + fields, + auth_settings, + stream, + timeout, + host, + ) + + return self.pool.apply_async( + self.__call_api, + ( + resource_path, + method, + path_params, + query_params, + headers, + body, + json, + fields, + auth_settings, + stream, + timeout, + host, + ) + ) + + def request( + self, + method: str, + url: str, + query_params: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, + 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, + stream=stream, + timeout=timeout, + headers=headers) + elif method == "HEAD": + return self.rest_client.HEAD(url, + query_params=query_params, + stream=stream, + timeout=timeout, + headers=headers) + elif method == "OPTIONS": + return self.rest_client.OPTIONS(url, + query_params=query_params, + headers=headers, + fields=fields, + stream=stream, + timeout=timeout, + body=body) + elif method == "POST": + return self.rest_client.POST(url, + query_params=query_params, + headers=headers, + fields=fields, + stream=stream, + timeout=timeout, + body=body) + elif method == "PUT": + return self.rest_client.PUT(url, + query_params=query_params, + headers=headers, + fields=fields, + stream=stream, + timeout=timeout, + body=body) + elif method == "PATCH": + return self.rest_client.PATCH(url, + query_params=query_params, + headers=headers, + fields=fields, + stream=stream, + timeout=timeout, + body=body) + elif method == "DELETE": + return self.rest_client.DELETE(url, + query_params=query_params, + 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, querys, auth_settings, + resource_path, method, body): + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param querys: 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(). + """ + 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']) +{{#if hasHttpSignatureMethods}} + 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, querys) + for key, value in auth_headers.items(): + headers.add(key, value) +{{/if}} + elif auth_setting['in'] == 'query': + querys.append((auth_setting['key'], auth_setting['value'])) + 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): + """ + 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 + ) -> typing.Dict[str, tuple[tuple[str, str], ...]]: + 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) + fields = self._serialize_form(cast_in_data, explode=True, name='') + if not fields: + return {} + return {'fields': fields} + + 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 content_type == 'application/json': + 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/modules/openapi-generator/src/main/resources/python-experimental/api_doc.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/api_doc.handlebars new file mode 100644 index 000000000000..6e74b8abb831 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/api_doc.handlebars @@ -0,0 +1,212 @@ +# {{packageName}}.{{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}} +{{/each}}{{/with}} + +{{#with operations}} +{{#each operation}} +# **{{{operationId}}}** +> {{#if returnType}}{{{returnType}}} {{/if}}{{{operationId}}}({{#each requiredParams}}{{#unless defaultValue}}{{paramName}}{{#if hasMore}}, {{/if}}{{/unless}}{{/each}}) + +{{{summary}}}{{#if notes}} + +{{{notes}}}{{/if}} + +### Example + +{{#if hasAuthMethods}} +{{#each authMethods}} +{{#if isBasic}} +{{#if isBasicBasic}} +* Basic Authentication ({{name}}): +{{/if}} +{{#if isBasicBearer}} +* Bearer{{#if bearerFormat}} ({{{bearerFormat}}}){{/if}} Authentication ({{name}}): +{{/if}} +{{/if}} +{{#if isApiKey}} +* Api Key Authentication ({{name}}): +{{/if}} +{{#if isOAuth}} +* OAuth Authentication ({{name}}): +{{/if}} +{{/each}} +{{/if}} +{{> api_doc_example }} +### Parameters +{{#if allParams}} + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + {{#with bodyParam}} +{{baseName}} | typing.Union[{{#each content}}{{#unless @first}}, {{/unless}}{{this.schema.baseName}}{{/each}}{{#unless required}}, Unset]{{else}}]{{/unless}} | {{#if required}}required{{else}}optional, default is unset{{/if}} | + {{/with}} + {{#if queryParams}} +query_params | RequestQueryParams | | + {{/if}} + {{#if headerParams}} +header_params | RequestHeaderParams | | + {{/if}} + {{#if pathParams}} +path_params | RequestPathParams | | + {{/if}} + {{#if cookieParams}} +cookie_params | RequestCookieParams | | + {{/if}} + {{#with bodyParam}} + {{#each content}} + {{#if @first}} +content_type | str | optional, default is '{{@key}}' | Selects the schema and serialization of the request body + {{/if}} + {{/each}} + {{/with}} + {{#if produces}} +accept_content_types | typing.Tuple[str] | default is ({{#each produces}}'{{this.mediaType}}', {{/each}}) | Tells the server the content type(s) that are accepted by the client + {{/if}} + {{#if servers}} +host_index | typing.Optional[int] | default is None | Allows one to select a different host + {{/if}} +stream | bool | default is False | if True then the response.content will be streamed and loaded from a file like object. When downloading a file, set this to True to force the code to deserialize the content to a FileSchema file +timeout | typing.Optional[typing.Union[int, typing.Tuple]] | default is None | the timeout used by the rest client +skip_deserialization | bool | default is False | when True, headers and body will be unset and an instance of api_client.ApiResponseWithoutDeserialization will be returned + {{#with bodyParam}} + +### body + {{#each content}} + {{#with this.schema}} +{{> api_doc_schema_type_hint }} + {{/with}} + {{/each}} + {{/with}} + {{#if queryParams}} + +### query_params +#### RequestQueryParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + {{#each queryParams}} +{{baseName}} | {{#with schema}}{{baseName}}{{/with}} | | {{#unless required}}optional{{/unless}} + {{/each}} + + {{#each queryParams}} + {{#with schema}} +{{> api_doc_schema_type_hint }} + {{/with}} + {{/each}} + {{/if}} + {{#if headerParams}} + +### header_params +#### RequestHeaderParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + {{#each headerParams}} +{{baseName}} | {{#with schema}}{{baseName}}{{/with}} | | {{#unless required}}optional{{/unless}} + {{/each}} + {{#each headerParams}} + {{#with schema}} +{{> api_doc_schema_type_hint }} + {{/with}} + {{/each}} + {{/if}} + {{#if pathParams}} + +### path_params +#### RequestPathParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + {{#each pathParams}} +{{baseName}} | {{#with schema}}{{baseName}}{{/with}} | | {{#unless required}}optional{{/unless}} + {{/each}} + {{#each pathParams}} + {{#with schema}} +{{> api_doc_schema_type_hint }} + {{/with}} + {{/each}} + {{/if}} + {{#if cookieParams}} + +### cookie_params +#### RequestCookieParams + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + {{#each cookieParams}} +{{baseName}} | {{#with schema}}{{baseName}}{{/with}} | | {{#unless required}}optional{{/unless}} + {{/each}} + {{#each cookieParams}} + {{#with schema}} +{{> api_doc_schema_type_hint }} + {{/with}} + {{/each}} + {{/if}} +{{else}} +This endpoint does not need any parameter. +{{/if}} + +### Return Types, Responses + +Code | Class | Description +------------- | ------------- | ------------- +n/a | api_client.ApiResponseWithoutDeserialization | When skip_deserialization is True this response is returned +{{#each responses}} +{{#if isDefault}} +default | ApiResponseForDefault | {{message}} {{description}} +{{else}} +{{code}} | ApiResponseFor{{code}} | {{message}} {{description}} +{{/if}} +{{/each}} +{{#each responses}} +{{#if isDefault}} + +#### ApiResponseForDefault +{{else}} + +#### ApiResponseFor{{code}} +{{/if}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- +response | urllib3.HTTPResponse | Raw response | +body | {{#unless content}}Unset{{else}}typing.Union[{{#each content}}{{this.schema.baseName}}, {{/each}}]{{/unless}} | {{#unless content}}body was not defined{{/unless}} | +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 }} +{{/with}} +{{/each}} +{{#if responseHeaders}} +#### ResponseHeadersFor{{code}} + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + {{#each responseHeaders}} +{{baseName}} | {{#with schema}}{{baseName}}{{/with}} | | {{#unless required}}optional{{/unless}} + {{/each}} + {{#each responseHeaders}} + {{#with schema}} +{{> api_doc_schema_type_hint }} + {{/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}} + +[[Back to top]](#) [[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-experimental/api_doc_example.handlebars new file mode 100644 index 000000000000..eaa2260e3f05 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/api_doc_example.handlebars @@ -0,0 +1,163 @@ +```python +import {{{packageName}}} +from {{packageName}}.{{apiPackage}} import {{classVarName}} +{{#each imports}} +{{{.}}} +{{/each}} +from pprint import pprint +{{> doc_auth_partial}} +# Enter a context with an instance of the API client +with {{{packageName}}}.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = {{classVarName}}.{{{classname}}}(api_client) +{{#if requiredParams}} + + # example passing only required values which don't have defaults set +{{#if pathParams}} + path_params = { + {{#each pathParams}} + {{#if required}} + '{{baseName}}': {{{example}}}, + {{/if}} + {{/each}} + } +{{/if}} +{{#if queryParams}} + query_params = { + {{#each queryParams}} + {{#if required}} + '{{baseName}}': {{{example}}}, + {{/if}} + {{/each}} + } +{{/if}} +{{#if cookieParams}} + cookie_params = { + {{#each cookieParams}} + {{#if required}} + '{{baseName}}': {{{example}}}, + {{/if}} + {{/each}} + } +{{/if}} +{{#if headerParams}} + header_params = { + {{#each headerParams}} + {{#if required}} + '{{baseName}}': {{{example}}}, + {{/if}} + {{/each}} + } +{{/if}} +{{#with bodyParam}} + {{#if required}} + body = {{{example}}} + {{/if}} +{{/with}} + try: +{{#if summary}} + # {{{summary}}} +{{/if}} + api_response = api_instance.{{{operationId}}}( + {{#if pathParams}} + path_params=path_params, + {{/if}} + {{#if queryParams}} + query_params=query_params, + {{/if}} + {{#if headerParams}} + header_params=header_params, + {{/if}} + {{#if cookieParams}} + cookie_params=cookie_params, + {{/if}} + {{#with bodyParam}} + {{#if required}} + body=body, + {{/if}} + {{/with}} + ) +{{#if returnType}} + pprint(api_response) +{{/if}} + except {{{packageName}}}.ApiException as e: + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) +{{/if}} +{{#if optionalParams}} + + # example passing only optional values +{{#if pathParams}} + path_params = { + {{#each pathParams}} + '{{baseName}}': {{{example}}}, + {{/each}} + } +{{/if}} +{{#if queryParams}} + query_params = { + {{#each queryParams}} + '{{baseName}}': {{{example}}}, + {{/each}} + } +{{/if}} +{{#if cookieParams}} + cookie_params = { + {{#each cookieParams}} + '{{baseName}}': {{{example}}}, + {{/each}} + } +{{/if}} +{{#if headerParams}} + header_params = { + {{#each headerParams}} + '{{baseName}}': {{{example}}}, + {{/each}} + } +{{/if}} +{{#with bodyParam}} + body = {{{example}}} +{{/with}} + try: +{{#if summary}} + # {{{summary}}} +{{/if}} + api_response = api_instance.{{{operationId}}}( + {{#if pathParams}} + path_params=path_params, + {{/if}} + {{#if queryParams}} + query_params=query_params, + {{/if}} + {{#if headerParams}} + header_params=header_params, + {{/if}} + {{#if cookieParams}} + cookie_params=cookie_params, + {{/if}} + {{#if bodyParam}} + body=body, + {{/if}} + ) +{{#if returnType}} + pprint(api_response) +{{/if}} + except {{{packageName}}}.ApiException as e: + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) +{{/if}} +{{#unless requiredParams}} +{{#unless optionalParams}} + + # example, this endpoint has no required or optional parameters + try: +{{#if summary}} + # {{{summary}}} +{{/if}} + api_response = api_instance.{{{operationId}}}() +{{#if returnType}} + pprint(api_response) +{{/if}} + except {{{packageName}}}.ApiException as e: + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) +{{/unless}} +{{/unless}} +``` 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 new file mode 100644 index 000000000000..0698320ad88d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/api_doc_schema_type_hint.handlebars @@ -0,0 +1,10 @@ + +#### {{baseName}} +{{#if complexType}} +Type | Description | Notes +------------- | ------------- | ------------- +[**{{dataType}}**]({{complexType}}.md) | {{description}} | {{#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 new file mode 100644 index 000000000000..a999b4b16c90 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/api_test.handlebars @@ -0,0 +1,34 @@ +# coding: utf-8 + +{{>partial_header}} + +import unittest + +import {{packageName}} +from {{packageName}}.api.{{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/configuration.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/configuration.handlebars new file mode 100644 index 000000000000..c0a0dc7dcc27 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/configuration.handlebars @@ -0,0 +1,636 @@ +# coding: utf-8 + +{{>partial_header}} + +import copy +import logging +{{#unless asyncio}} +import multiprocessing +{{/unless}} +import sys +import urllib3 + +from http import client as http_client +from {{packageName}}.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. +{{#if hasHttpSignatureMethods}} + :param signing_info: Configuration parameters for the HTTP signature security scheme. + Must be an instance of {{{packageName}}}.signing.HttpSigningConfiguration +{{/if}} + :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. + +{{#if hasAuthMethods}} + :Example: +{{#if hasApiKeyMethods}} + + 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 = {{{packageName}}}.Configuration( + api_key={'cookieAuth': 'abc123'} + api_key_prefix={'cookieAuth': 'JSESSIONID'} +) + + The following cookie will be added to the HTTP request: + Cookie: JSESSIONID abc123 +{{/if}} +{{#if hasHttpBasicMethods}} + + 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 = {{{packageName}}}.Configuration( + username='the-user', + password='the-password', +) + +{{/if}} +{{#if hasHttpSignatureMethods}} + + 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 {{{packageName}}}.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 = {{{packageName}}}.Configuration( + signing_info = {{{packageName}}}.signing.HttpSigningConfiguration( + key_id = 'my-key-id', + private_key_path = 'rsa.pem', + signing_scheme = {{{packageName}}}.signing.SCHEME_HS2019, + signing_algorithm = {{{packageName}}}.signing.ALGORITHM_RSASSA_PSS, + signed_headers = [{{{packageName}}}.signing.HEADER_REQUEST_TARGET, + {{{packageName}}}.signing.HEADER_CREATED, + {{{packageName}}}.signing.HEADER_EXPIRES, + {{{packageName}}}.signing.HEADER_HOST, + {{{packageName}}}.signing.HEADER_DATE, + {{{packageName}}}.signing.HEADER_DIGEST, + 'Content-Type', + 'User-Agent' + ], + signature_max_validity = datetime.timedelta(minutes=5) + ) +) +{{/if}} +{{/if}} + """ + + _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="", +{{#if hasHttpSignatureMethods}} + signing_info=None, +{{/if}} + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, + ): + """Constructor + """ + self._base_path = "{{{basePath}}}" 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 hasHttpSignatureMethods}} + if signing_info is not None: + signing_info.host = host + self.signing_info = signing_info + """The HTTP signing configuration + """ +{{/if}} +{{#if hasOAuthMethods}} + self.access_token = None + """access token for OAuth/Bearer + """ +{{/if}} +{{#unless hasOAuthMethods}} +{{#if hasBearerMethods}} + self.access_token = None + """access token for OAuth/Bearer + """ +{{/if}} +{{/unless}} + self.logger = {} + """Logging Settings + """ + self.logger["package_logger"] = logging.getLogger("{{packageName}}") + 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. + """ + + {{#if asyncio}} + self.connection_pool_maxsize = 100 + """This value is passed to the aiohttp to limit simultaneous connections. + Default values is 100, None means no-limit. + """ + {{/if}} + {{#unless asyncio}} + 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. + """ + {{/unless}} + + 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 hasHttpSignatureMethods}} + 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 +{{/if}} + + @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 = {} +{{#each authMethods}} +{{#if isApiKey}} + if '{{name}}' in self.api_key{{#each vendorExtensions.x-auth-id-alias}} or '{{.}}' in self.api_key{{/each}}: + auth['{{name}}'] = { + 'type': 'api_key', + 'in': {{#if isKeyInCookie}}'cookie'{{/if}}{{#if isKeyInHeader}}'header'{{/if}}{{#if isKeyInQuery}}'query'{{/if}}, + 'key': '{{keyParamName}}', + 'value': self.get_api_key_with_prefix( + '{{name}}',{{#each vendorExtensions.x-auth-id-alias}} + alias='{{.}}',{{/each}} + ), + } +{{/if}} +{{#if isBasic}} + {{#if isBasicBasic}} + if self.username is not None and self.password is not None: + auth['{{name}}'] = { + 'type': 'basic', + 'in': 'header', + 'key': 'Authorization', + 'value': self.get_basic_auth_token() + } + {{/if}} + {{#if isBasicBearer}} + if self.access_token is not None: + auth['{{name}}'] = { + 'type': 'bearer', + 'in': 'header', + {{#if bearerFormat}} + 'format': '{{{bearerFormat}}}', + {{/if}} + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } + {{/if}} + {{#if isHttpSignature}} + if self.signing_info is not None: + auth['{{name}}'] = { + 'type': 'http-signature', + 'in': 'header', + 'key': 'Authorization', + 'value': None # Signature headers are calculated for every HTTP request + } + {{/if}} +{{/if}} +{{#if isOAuth}} + if self.access_token is not None: + auth['{{name}}'] = { + 'type': 'oauth2', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } +{{/if}} +{{/each}} + 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: {{version}}\n"\ + "SDK Package Version: {{packageVersion}}".\ + 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 [ + {{#each servers}} + { + 'url': "{{{url}}}", + 'description': "{{{description}}}{{#unless description}}No description provided{{/unless}}", + {{#each variables}} + {{#if @first}} + 'variables': { + {{/if}} + '{{{name}}}': { + 'description': "{{{description}}}{{#unless description}}No description provided{{/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}} + }{{#unless @last}},{{/unless}} + {{/each}} + ] + + 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/modules/openapi-generator/src/main/resources/python-experimental/doc_auth_partial.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/doc_auth_partial.handlebars new file mode 100644 index 000000000000..b16451d867e0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/doc_auth_partial.handlebars @@ -0,0 +1,109 @@ +# Defining the host is optional and defaults to {{{basePath}}} +# See configuration.py for a list of all supported configuration parameters. +configuration = {{{packageName}}}.Configuration( + host = "{{{basePath}}}" +) + +{{#if hasAuthMethods}} +# 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. +{{#each authMethods}} +{{#if isBasic}} +{{#if isBasicBasic}} + +# Configure HTTP basic authorization: {{{name}}} +configuration = {{{packageName}}}.Configuration( + username = 'YOUR_USERNAME', + password = 'YOUR_PASSWORD' +) +{{/if}} +{{#if isBasicBearer}} + +# Configure Bearer authorization{{#if bearerFormat}} ({{{bearerFormat}}}){{/if}}: {{{name}}} +configuration = {{{packageName}}}.Configuration( + access_token = 'YOUR_BEARER_TOKEN' +) +{{/if}} +{{#if isHttpSignature}} + +# Configure HTTP message signature: {{{name}}} +# 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 {{{packageName}}}.signing for a list of all supported parameters. +configuration = {{{packageName}}}.Configuration( + host = "{{{basePath}}}", + signing_info = {{{packageName}}}.signing.HttpSigningConfiguration( + key_id = 'my-key-id', + private_key_path = 'private_key.pem', + private_key_passphrase = 'YOUR_PASSPHRASE', + signing_scheme = {{{packageName}}}.signing.SCHEME_HS2019, + signing_algorithm = {{{packageName}}}.signing.ALGORITHM_ECDSA_MODE_FIPS_186_3, + hash_algorithm = {{{packageName}}}.signing.SCHEME_RSA_SHA256, + signed_headers = [ + {{{packageName}}}.signing.HEADER_REQUEST_TARGET, + {{{packageName}}}.signing.HEADER_CREATED, + {{{packageName}}}.signing.HEADER_EXPIRES, + {{{packageName}}}.signing.HEADER_HOST, + {{{packageName}}}.signing.HEADER_DATE, + {{{packageName}}}.signing.HEADER_DIGEST, + 'Content-Type', + 'Content-Length', + 'User-Agent' + ], + signature_max_validity = datetime.timedelta(minutes=5) + ) +) +{{/if}} +{{/if}} +{{#if isApiKey}} + +# Configure API key authorization: {{{name}}} +configuration.api_key['{{{name}}}'] = 'YOUR_API_KEY' + +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# configuration.api_key_prefix['{{name}}'] = 'Bearer' +{{/if}} +{{#if isOAuth}} + +# Configure OAuth2 access token for authorization: {{{name}}} +configuration = {{{packageName}}}.Configuration( + host = "{{{basePath}}}" +) +configuration.access_token = 'YOUR_ACCESS_TOKEN' +{{/if}} +{{/each}} +{{/if}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/endpoint.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/endpoint.handlebars new file mode 100644 index 000000000000..f6de978e4781 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/endpoint.handlebars @@ -0,0 +1,549 @@ +# coding: utf-8 + +{{>partial_header}} + +from dataclasses import dataclass +import re # noqa: F401 +import sys # noqa: F401 +import typing +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 }} + +{{#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( + schema={{this.schema.baseName}}), +{{/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': "{{{description}}}{{#unless description}}No description provided{{/unless}}", + {{#each variables}} + {{#if @first}} + 'variables': { + {{/if}} + '{{{name}}}': { + 'description': "{{{description}}}{{#unless description}}No description provided{{/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}} + {{this.schema.baseName}}, +{{/each}} + ] + headers: ResponseHeadersFor{{code}} +{{else}} +{{#or responseHeaders content}} +{{#if responseHeaders}} + headers: ResponseHeadersFor{{code}} + body: Unset = unset +{{else}} + body: typing.Union[ +{{#each content}} + {{this.schema.baseName}}, +{{/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( + schema={{this.schema.baseName}}), +{{#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}} + {{#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) + {{/if}} + {{#if queryParams}} + + _query_params = [] + for parameter in ( + {{#each queryParams}} + request_query_{{paramName}}, + {{/each}} + ): + parameter_data = query_params.get(parameter.name, unset) + if parameter_data is unset: + continue + serialized_data = parameter.serialize(parameter_data) + _query_params.extend(serialized_data) + {{/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=_path, + method=_method, + {{#if pathParams}} + path_params=_path_params, + {{/if}} + {{#if queryParams}} + query_params=tuple(_query_params), + {{/if}} + {{#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_body_serialization.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/endpoint_body_serialization.handlebars new file mode 100644 index 000000000000..f00d9f05d278 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/endpoint_body_serialization.handlebars @@ -0,0 +1,6 @@ +serialized_data = request_body_{{paramName}}.serialize(body, content_type) +_headers.add('Content-Type', content_type) +if 'fields' in serialized_data: + _fields = serialized_data['fields'] +elif 'body' in serialized_data: + _body = serialized_data['body'] \ No newline at end of file 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 new file mode 100644 index 000000000000..4b9d815af83e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/endpoint_parameter.handlebars @@ -0,0 +1,17 @@ +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/exceptions.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/exceptions.handlebars new file mode 100644 index 000000000000..fa5f75347892 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/exceptions.handlebars @@ -0,0 +1,129 @@ +# coding: utf-8 + +{{>partial_header}} + + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None): + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + 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 + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None): + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__(self, status=None, reason=None, api_response: '{{packageName}}.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 + self.body = None + self.headers = None + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.body: + error_message += "HTTP response body: {0}\n".format(self.body) + + return error_message + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/modules/openapi-generator/src/main/resources/python-experimental/git_push.sh.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/git_push.sh.handlebars new file mode 100644 index 000000000000..8b3f689c9121 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/git_push.sh.handlebars @@ -0,0 +1,58 @@ +#!/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="{{{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-experimental/gitignore.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/gitignore.handlebars new file mode 100644 index 000000000000..a62e8aba43f8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/gitignore.handlebars @@ -0,0 +1,67 @@ +# 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/modules/openapi-generator/src/main/resources/python-experimental/gitlab-ci.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/gitlab-ci.handlebars new file mode 100644 index 000000000000..0cfe8f74ecfc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/gitlab-ci.handlebars @@ -0,0 +1,29 @@ +# 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 + {{#if useNose}} + - nosetests + {{/if}} + {{#unless useNose}} + - pytest --cov={{{packageName}}} + {{/unless}} + +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/modules/openapi-generator/src/main/resources/python-experimental/model.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model.handlebars new file mode 100644 index 000000000000..d8c1e63ae4d4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model.handlebars @@ -0,0 +1,17 @@ +# coding: utf-8 + +{{>partial_header}} + +import re # noqa: F401 +import sys # noqa: F401 +import typing # 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 new file mode 100644 index 000000000000..2c4136a142ae --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_doc.handlebars @@ -0,0 +1,9 @@ +{{#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 new file mode 100644 index 000000000000..6aef3311b6e3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/composed_schemas.handlebars @@ -0,0 +1,86 @@ +@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 +{{#with composedSchemas}} +{{#each allOf}} +{{#unless complexType}} +{{#unless isAnyType}} + {{> model_templates/schema }} +{{/unless}} +{{/unless}} +{{#if isAnyType}} + {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}} = AnyTypeSchema +{{/if}} +{{/each}} +{{#each oneOf}} +{{#unless complexType}} +{{#unless isAnyType}} + {{> model_templates/schema }} +{{/unless}} +{{/unless}} +{{#if isAnyType}} + {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}} = AnyTypeSchema +{{/if}} +{{/each}} +{{#each anyOf}} +{{#unless complexType}} +{{#unless isAnyType}} + {{> model_templates/schema }} +{{/unless}} +{{/unless}} +{{#if isAnyType}} + {{#if this.classname}}{{classname}}{{else}}{{#if nameInSnakeCase}}{{name}}{{else}}{{baseName}}{{/if}}{{/if}} = AnyTypeSchema +{{/if}} +{{/each}} +{{/with}} + return { + 'allOf': [ +{{#with composedSchemas}} +{{#each allOf}} +{{#if complexType}} + {{complexType}}, +{{/if}} +{{#unless complexType}} + {{#if nameInSnakeCase}}{{name}}{{/if}}{{#unless nameInSnakeCase}}{{baseName}}{{/unless}}, +{{/unless}} +{{/each}} + ], + 'oneOf': [ +{{#each oneOf}} +{{#if complexType}} + {{complexType}}, +{{/if}} +{{#unless complexType}} +{{#if isAnyType}} + AnyTypeSchema, +{{/if}} +{{#unless isAnyType}} + {{#if nameInSnakeCase}}{{name}}{{/if}}{{#unless nameInSnakeCase}}{{baseName}}{{/unless}}, +{{/unless}} +{{/unless}} +{{/each}} + ], + 'anyOf': [ +{{#each anyOf}} +{{#if complexType}} + {{complexType}}, +{{/if}} +{{#unless complexType}} +{{#if isAnyType}} + AnyTypeSchema, +{{/if}} +{{#unless isAnyType}} + {{#if nameInSnakeCase}}{{name}}{{/if}}{{#unless nameInSnakeCase}}{{baseName}}{{/unless}}, +{{/unless}} +{{/unless}} +{{/each}} +{{/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 new file mode 100644 index 000000000000..15338b38f1db --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/dict_partial.handlebars @@ -0,0 +1,54 @@ +{{#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 new file mode 100644 index 000000000000..ea2cb759fbef --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/enum_value_to_name.handlebars @@ -0,0 +1,12 @@ +_SchemaEnumMaker( + enum_value_to_name={ +{{#if isNull}} + 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 new file mode 100644 index 000000000000..5cbc68dc173e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/enums.handlebars @@ -0,0 +1,16 @@ +{{#if isNull}} + +@classmethod +@property +def NONE(cls): + return cls._enum_by_value[None](None) +{{/if}} +{{#with allowableValues}} +{{#each enumVars}} + +@classmethod +@property +def {{name}}(cls): + return cls._enum_by_value[{{{value}}}]({{{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 new file mode 100644 index 000000000000..0741ba482fe6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/imports_schema_types.handlebars @@ -0,0 +1,41 @@ +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) diff --git a/modules/openapi-generator/src/main/resources/python-experimental/model_templates/imports_schemas.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/imports_schemas.handlebars new file mode 100644 index 000000000000..b925cf92c698 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/imports_schemas.handlebars @@ -0,0 +1,6 @@ +{{#each imports}} +{{#if @first}} + +{{/if}} +{{{.}}} +{{/each}} \ No newline at end of file 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 new file mode 100644 index 000000000000..bb220e4b8f3a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/new.handlebars @@ -0,0 +1,53 @@ +def __new__( + cls, + *args: typing.Union[{{#if isAnyType}}dict, frozendict, str, date, datetime, int, float, 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}} + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, +{{#with additionalProperties}} + **kwargs: typing.Type[Schema], +{{/with}} +): + 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}} + _instantiation_metadata=_instantiation_metadata, +{{#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 new file mode 100644 index 000000000000..7523d39f0eae --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema.handlebars @@ -0,0 +1,46 @@ +{{#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 new file mode 100644 index 000000000000..18527e02effd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_composed_or_anytype.handlebars @@ -0,0 +1,67 @@ + + +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}}none_type, {{/if}}{{#if isString}}str, {{/if}}{{#if isByteArray}}str, {{/if}}{{#if isUnboundedInteger}}Decimal, {{/if}}{{#if isShort}}Decimal, {{/if}}{{#if isLong}}Decimal, {{/if}}{{#if isFloat}}Decimal, {{/if}}{{#if isDouble}}Decimal, {{/if}}{{#if isNumber}}Decimal, {{/if}}{{#if isDate}}str, {{/if}}{{#if isDateTime}}str, {{/if}}{{#if isBoolean}}bool, {{/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}} + + Attributes: +{{#each vars}} + {{baseName}} ({{#if isArray}}tuple,{{/if}}{{#if isBoolean}}bool,{{/if}}{{#if isDate}}date,{{/if}}{{#if isDateTime}}datetime,{{/if}}{{#if isMap}}dict,{{/if}}{{#if isFloat}}float,{{/if}}{{#if isNumber}}float,{{/if}}{{#if isUnboundedInteger}}int,{{/if}}{{#if isShort}}int,{{/if}}{{#if isLong}}int,{{/if}}{{#if isString}}str,{{/if}}{{#if isByteArray}}str,{{/if}}{{#if isNull}} none_type,{{/if}}): {{#if description}}{{description}}{{/if}} +{{/each}} +{{#if hasValidation}} + _validations (dict): the validations which apply to the current Schema + 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. +{{/if}} +{{#with additionalProperties}} + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties +{{/with}} +{{#if getHasDiscriminatorWithNonEmptyMapping}} + _discriminator(cls) -> dict: the key is the required discriminator propertyName + the value is a dict mapping from a string name to the corresponding Schema class +{{/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 new file mode 100644 index 000000000000..f811b092e506 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_dict.handlebars @@ -0,0 +1,42 @@ + + +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}} + + Attributes: +{{#each vars}} + {{baseName}} ({{#if isArray}}tuple,{{/if}}{{#if isBoolean}}bool,{{/if}}{{#if isDate}}date,{{/if}}{{#if isDateTime}}datetime,{{/if}}{{#if isMap}}dict,{{/if}}{{#if isFloat}}float,{{/if}}{{#if isDouble}}float,{{/if}}{{#if isNumber}}int, float,{{/if}}{{#if isUnboundedInteger}}int,{{/if}}{{#if isShort}}int,{{/if}}{{#if isLong}}int,{{/if}}{{#if isString}}str,{{/if}}{{#if isByteArray}}str,{{/if}}{{#if isNull}} none_type,{{/if}}): {{#if description}}{{description}}{{/if}} +{{/each}} +{{#if hasValidation}} + _validations (dict): the validations which apply to the current Schema + 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. +{{/if}} +{{#with additionalProperties}} + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties +{{/with}} +{{#if getHasDiscriminatorWithNonEmptyMapping}} + _discriminator(cls) -> dict: the key is the required discriminator propertyName + the value is a dict mapping from a string name to the corresponding Schema class +{{/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 new file mode 100644 index 000000000000..8617eeb0559e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_list.handlebars @@ -0,0 +1,39 @@ + + +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}} + + Attributes: + _items (Schema): the schema definition of the array items +{{#if hasValidation}} + _validations (dict): the validations which apply to the current Schema + 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. +{{/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 new file mode 100644 index 000000000000..06ba2af1917a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/schema_simple.handlebars @@ -0,0 +1,35 @@ + + +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}} + + Attributes: +{{#if hasValidation}} + _validations (dict): the validations which apply to the current Schema + 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. +{{/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 new file mode 100644 index 000000000000..2384ac063d24 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/validations.handlebars @@ -0,0 +1,50 @@ +_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}} +{{#if maxProperties}} + max_properties={{maxProperties}}, +{{/if}} +{{#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 new file mode 100644 index 000000000000..14b4c5e0648f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/var_equals_cls.handlebars @@ -0,0 +1 @@ +{{#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 isUnboundedInteger}}Int{{/if}}{{#if isShort}}Int32{{/if}}{{#if isLong}}Int64{{/if}}{{#if isFloat}}Float32{{/if}}{{#if isDouble}}Float64{{/if}}{{#if isNumber}}Number{{/if}}{{#if isDate}}Date{{/if}}{{#if isDateTime}}DateTime{{/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 new file mode 100644 index 000000000000..0b345344c432 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_templates/xbase_schema.handlebars @@ -0,0 +1,48 @@ +{{#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 isDate}} +Date{{#if getHasMultipleTypes}}Base,{{else}}Schema{{/if}} +{{/if}} +{{#if isDateTime}} +DateTime{{#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/model_test.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/model_test.handlebars new file mode 100644 index 000000000000..094d7f49b65d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/model_test.handlebars @@ -0,0 +1,33 @@ +# coding: utf-8 + +{{>partial_header}} + +import sys +import unittest + +import {{packageName}} +{{#each models}} +{{#with model}} +from {{modelPackage}}.{{classFilename}} import {{classname}} + + +class Test{{classname}}(unittest.TestCase): + """{{classname}} unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_{{classname}}(self): + """Test {{classname}}""" + # FIXME: construct object with mandatory attributes with example values + # model = {{classname}}() # noqa: E501 + pass + +{{/with}} +{{/each}} + +if __name__ == '__main__': + unittest.main() diff --git a/modules/openapi-generator/src/main/resources/python-experimental/partial_header.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/partial_header.handlebars new file mode 100644 index 000000000000..19b633be2579 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/partial_header.handlebars @@ -0,0 +1,17 @@ +""" +{{#if appName}} + {{{appName}}} +{{/if}} + +{{#if appDescription}} + {{{appDescription}}} # noqa: E501 +{{/if}} + + {{#if version}} + The version of the OpenAPI document: {{{version}}} + {{/if}} + {{#if infoEmail}} + Contact: {{{infoEmail}}} + {{/if}} + Generated by: https://openapi-generator.tech +""" diff --git a/modules/openapi-generator/src/main/resources/python-experimental/requirements.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/requirements.handlebars new file mode 100644 index 000000000000..c9227e58a1be --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/requirements.handlebars @@ -0,0 +1,5 @@ +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/rest.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/rest.handlebars new file mode 100644 index 000000000000..e30831938f15 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/rest.handlebars @@ -0,0 +1,251 @@ +# coding: utf-8 + +{{>partial_header}} + +import logging +import ssl +from urllib.parse import urlencode +import typing + +import certifi +import urllib3 +from urllib3._collections import HTTPHeaderDict + +from {{packageName}}.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, + query_params: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, + 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 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]) + + if 'Content-Type' not in headers: + headers['Content-Type'] = 'application/json' + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + if query_params: + url += '?' + urlencode(query_params) + if 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, + fields=query_params, + 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, query_params=None, stream=False, + timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("GET", url, + headers=headers, + stream=stream, + timeout=timeout, + query_params=query_params, fields=fields) + + def HEAD(self, url, headers=None, query_params=None, stream=False, + timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("HEAD", url, + headers=headers, + stream=stream, + timeout=timeout, + query_params=query_params, fields=fields) + + def OPTIONS(self, url, headers=None, query_params=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("OPTIONS", url, + headers=headers, + query_params=query_params, + stream=stream, + timeout=timeout, + body=body, fields=fields) + + def DELETE(self, url, headers=None, query_params=None, body=None, + stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("DELETE", url, + headers=headers, + query_params=query_params, + stream=stream, + timeout=timeout, + body=body, fields=fields) + + def POST(self, url, headers=None, query_params=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("POST", url, + headers=headers, + query_params=query_params, + stream=stream, + timeout=timeout, + body=body, fields=fields) + + def PUT(self, url, headers=None, query_params=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("PUT", url, + headers=headers, + query_params=query_params, + stream=stream, + timeout=timeout, + body=body, fields=fields) + + def PATCH(self, url, headers=None, query_params=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("PATCH", url, + headers=headers, + query_params=query_params, + stream=stream, + timeout=timeout, + body=body, fields=fields) 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 new file mode 100644 index 000000000000..556d2cbb5f95 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/schema_doc.handlebars @@ -0,0 +1,32 @@ + +{{#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}} | {{description}} | {{#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}} | {{description}} | {{#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}} | {{description}} | {{#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 new file mode 100644 index 000000000000..b238468f73a0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/schemas.handlebars @@ -0,0 +1,1987 @@ +# coding: utf-8 + +{{>partial_header}} + +from collections import defaultdict +from datetime import date, datetime, timedelta # noqa: F401 +from dataclasses import dataclass +import functools +from decimal import Decimal +import io +import os +import re +import tempfile +import typing + +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)): + 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 update(d: dict, u: dict): + """ + Adds u to d + Where each dict is defaultdict(set) + """ + for k, v in u.items(): + d[k] = d[k].union(v) + return d + + +class InstantiationMetadata: + """ + A class to store metadata that is needed when instantiating OpenApi Schema subclasses + """ + def __init__( + self, + path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), + from_server: bool = False, + configuration: typing.Optional[Configuration] = None, + base_classes: typing.FrozenSet[typing.Type] = frozenset(), + path_to_schemas: typing.Optional[typing.Dict[str, typing.Set[typing.Type]]] = None, + ): + """ + 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) + 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 + configuration: the Configuration instance to use + This is needed because in Configuration: + - one can disable validation checking + base_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. + path_to_schemas: a dict that goes from path to a list of classes at each path location + """ + self.path_to_item = path_to_item + self.from_server = from_server + self.configuration = configuration + self.base_classes = base_classes + if path_to_schemas is None: + path_to_schemas = defaultdict(set) + self.path_to_schemas = path_to_schemas + + def __repr__(self): + return str(self.__dict__) + + def __eq__(self, other): + if not isinstance(other, InstantiationMetadata): + return False + return self.__dict__ == other.__dict__ + + +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, + _instantiation_metadata: InstantiationMetadata): + + if (cls.__is_json_validation_enabled('maxLength', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('minLength', _instantiation_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=_instantiation_metadata.path_to_item + ) + + checked_value = input_values + if (cls.__is_json_validation_enabled('pattern', _instantiation_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=_instantiation_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=_instantiation_metadata.path_to_item + ) + + @classmethod + def __check_tuple_validations( + cls, validations, input_values, + _instantiation_metadata: InstantiationMetadata): + + if (cls.__is_json_validation_enabled('maxItems', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('minItems', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('uniqueItems', _instantiation_metadata.configuration) and + 'unique_items' in validations and validations['unique_items'] and input_values): + unique_items = [] + # print(validations) + for item in input_values: + if item not in unique_items: + unique_items.append(item) + 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=_instantiation_metadata.path_to_item + ) + + @classmethod + def __check_dict_validations( + cls, validations, input_values, + _instantiation_metadata: InstantiationMetadata): + + if (cls.__is_json_validation_enabled('maxProperties', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('minProperties', _instantiation_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=_instantiation_metadata.path_to_item + ) + + @classmethod + def __check_numeric_validations( + cls, validations, input_values, + _instantiation_metadata: InstantiationMetadata): + + if cls.__is_json_validation_enabled('multipleOf', + _instantiation_metadata.configuration) and 'multiple_of' in validations: + multiple_of_values = validations['multiple_of'] + for multiple_of_value in multiple_of_values: + if (isinstance(input_values, 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=_instantiation_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', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('maximum', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('exclusiveMinimum', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('minimum', _instantiation_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=_instantiation_metadata.path_to_item + ) + + @classmethod + def _check_validations_for_types( + cls, + validations, + input_values, + _instantiation_metadata: InstantiationMetadata + ): + if isinstance(input_values, str): + cls.__check_str_validations(validations, input_values, _instantiation_metadata) + elif isinstance(input_values, tuple): + cls.__check_tuple_validations(validations, input_values, _instantiation_metadata) + elif isinstance(input_values, frozendict): + cls.__check_dict_validations(validations, input_values, _instantiation_metadata) + elif isinstance(input_values, Decimal): + cls.__check_numeric_validations(validations, input_values, _instantiation_metadata) + try: + return super()._validate_validations_pass(input_values, _instantiation_metadata) + except AttributeError: + return True + + +class Validator(typing.Protocol): + def _validate_validations_pass( + cls, + input_values, + _instantiation_metadata: InstantiationMetadata + ): + 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_validations_pass( + cls, + input_values, + _instantiation_metadata: InstantiationMetadata + ): + cls._check_validations_for_types(validations, input_values, _instantiation_metadata) + try: + return super()._validate_validations_pass(input_values, _instantiation_metadata) + except AttributeError: + return True + + return SchemaValidator + + +class TypeChecker(typing.Protocol): + @classmethod + def _validate_type( + cls, arg_simple_class: type + ) -> typing.Tuple[type]: + pass + + +def _SchemaTypeChecker(union_type_cls: typing.Union[typing.Any]) -> TypeChecker: + 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: + @classmethod + def _validate_type(cls, arg_simple_class: type): + if arg_simple_class not in union_classes: + return union_classes + try: + return super()._validate_type(arg_simple_class) + except AttributeError: + return tuple() + + return SchemaTypeChecker + + +class EnumMakerBase: + @classmethod + @property + def _enum_by_value( + cls + ) -> type: + enum_classes = {} + if not hasattr(cls, "_enum_value_to_name"): + return enum_classes + for enum_value, enum_name in cls._enum_value_to_name.items(): + base_class = type(enum_value) + if base_class is none_type: + enum_classes[enum_value] = get_new_class( + "Dynamic" + cls.__name__, (cls, NoneClass)) + log_cache_usage(get_new_class) + elif base_class is bool: + enum_classes[enum_value] = get_new_class( + "Dynamic" + cls.__name__, (cls, BoolClass)) + log_cache_usage(get_new_class) + else: + enum_classes[enum_value] = get_new_class( + "Dynamic" + cls.__name__, (cls, Singleton, base_class)) + log_cache_usage(get_new_class) + return enum_classes + + +class EnumMakerInterface(typing.Protocol): + @classmethod + @property + def _enum_value_to_name( + cls + ) -> typing.Dict[typing.Union[str, Decimal, bool, none_type], str]: + pass + + @classmethod + @property + def _enum_by_value( + cls + ) -> type: + pass + + +def _SchemaEnumMaker(enum_value_to_name: typing.Dict[typing.Union[str, Decimal, bool, none_type], str]) -> EnumMakerInterface: + class SchemaEnumMaker(EnumMakerBase): + @classmethod + @property + def _enum_value_to_name( + cls + ) -> typing.Dict[typing.Union[str, 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 + + return SchemaEnumMaker + + +class Singleton: + """ + Enums and singletons are the same + The same instance is returned for a given key of (cls, arg) + """ + # TODO use bidict to store this so boolean enums can move through it in reverse to get their own arg value? + _instances = {} + + def __new__(cls, *args, **kwargs): + if not args: + raise ValueError('arg must be passed') + arg = args[0] + key = (cls, arg) + if key not in cls._instances: + if arg in {None, True, False}: + inst = super().__new__(cls) + # inst._value = arg + cls._instances[key] = inst + else: + cls._instances[key] = super().__new__(cls, arg) + return cls._instances[key] + + def __repr__(self): + return '({}, {})'.format(self.__class__.__name__, self) + + +class NoneClass(Singleton): + @classmethod + @property + def NONE(cls): + return cls(None) + + def is_none(self) -> bool: + return True + + 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 key[1] + raise ValueError('Unable to find the boolean value of this instance') + + def is_true(self): + return bool(self) + + def is_false(self): + return bool(self) + + +class BoolBase: + pass + + +class NoneBase: + pass + + +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') + + +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], _instantiation_metadata: InstantiationMetadata): + 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, _instantiation_metadata.path_to_item) + ) + + @classmethod + def _validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + DateBase _validate + """ + cls._validate_format(args[0], _instantiation_metadata=_instantiation_metadata) + return super()._validate(*args, _instantiation_metadata=_instantiation_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], _instantiation_metadata: InstantiationMetadata): + 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, _instantiation_metadata.path_to_item) + ) + + @classmethod + def _validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + DateTimeBase _validate + """ + cls._validate_format(args[0], _instantiation_metadata=_instantiation_metadata) + return super()._validate(*args, _instantiation_metadata=_instantiation_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, _instantiation_metadata: InstantiationMetadata): + """ + 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 = defaultdict(set) + for i, value in enumerate(list_items): + if isinstance(value, item_cls): + continue + item_instantiation_metadata = InstantiationMetadata( + from_server=_instantiation_metadata.from_server, + configuration=_instantiation_metadata.configuration, + path_to_item=_instantiation_metadata.path_to_item+(i,) + ) + other_path_to_schemas = item_cls._validate( + value, _instantiation_metadata=item_instantiation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def _validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + 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 + """ + arg = args[0] + _path_to_schemas = super()._validate(*args, _instantiation_metadata=_instantiation_metadata) + if not isinstance(arg, tuple): + return _path_to_schemas + if cls in _instantiation_metadata.base_classes: + # we have already moved through this class so stop here + return _path_to_schemas + _instantiation_metadata.base_classes |= frozenset({cls}) + other_path_to_schemas = cls._validate_items(arg, _instantiation_metadata=_instantiation_metadata) + update(_path_to_schemas, other_path_to_schemas) + return _path_to_schemas + + @classmethod + def _get_items(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + ''' + ListBase _get_items + ''' + _instantiation_metadata = InstantiationMetadata() if _instantiation_metadata is None else _instantiation_metadata + + list_items = args[0] + 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 = _instantiation_metadata.path_to_item+(i,) + if item_path_to_item in _instantiation_metadata.path_to_schemas: + item_cls = _instantiation_metadata.path_to_schemas[item_path_to_item] + else: + item_cls = cls_item_cls + + if isinstance(value, item_cls): + cast_items.append(value) + continue + item_instantiation_metadata = InstantiationMetadata( + configuration=_instantiation_metadata.configuration, + from_server=_instantiation_metadata.from_server, + path_to_item=item_path_to_item, + path_to_schemas=_instantiation_metadata.path_to_schemas, + ) + + if _instantiation_metadata.from_server: + new_value = item_cls._from_openapi_data(value, _instantiation_metadata=item_instantiation_metadata) + else: + new_value = item_cls(value, _instantiation_metadata=item_instantiation_metadata) + cast_items.append(new_value) + + return cast_items + + +class Discriminable: + @classmethod + def _ensure_discriminator_value_present(cls, disc_property_name: str, _instantiation_metadata: InstantiationMetadata, *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, _instantiation_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, _instantiation_metadata: InstantiationMetadata): + """ + 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 = defaultdict(set) + 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, _instantiation_metadata.path_to_item+(property_name,) + )) + if isinstance(value, schema): + continue + arg_instantiation_metadata = InstantiationMetadata( + from_server=_instantiation_metadata.from_server, + configuration=_instantiation_metadata.configuration, + path_to_item=_instantiation_metadata.path_to_item+(property_name,) + ) + other_path_to_schemas = schema._validate(value, _instantiation_metadata=arg_instantiation_metadata) + update(path_to_schemas, other_path_to_schemas) + _instantiation_metadata.path_to_schemas.update(arg_instantiation_metadata.path_to_schemas) + return path_to_schemas + + @classmethod + def _validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + 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 args and isinstance(args[0], cls): + # an instance of the correct type was passed in + return {} + arg = args[0] + _path_to_schemas = super()._validate(*args, _instantiation_metadata=_instantiation_metadata) + if not isinstance(arg, frozendict): + return _path_to_schemas + cls._validate_arg_presence(args[0]) + other_path_to_schemas = cls._validate_args(args[0], _instantiation_metadata=_instantiation_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, _instantiation_metadata, *args) + 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()), + _instantiation_metadata.path_to_item + (disc_prop_name,) + ) + ) + if discriminated_cls in _instantiation_metadata.base_classes: + # we have already moved through this class so stop here + return _path_to_schemas + _instantiation_metadata.base_classes |= frozenset({cls}) + other_path_to_schemas = discriminated_cls._validate(*args, _instantiation_metadata=_instantiation_metadata) + 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], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + 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 + + _instantiation_metadata = InstantiationMetadata() if _instantiation_metadata is None else _instantiation_metadata + + for property_name_js, value in arg.items(): + property_cls = getattr(cls, property_name_js, cls._additional_properties) + property_path_to_item = _instantiation_metadata.path_to_item+(property_name_js,) + stored_property_cls = _instantiation_metadata.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 + + prop_instantiation_metadata = InstantiationMetadata( + configuration=_instantiation_metadata.configuration, + from_server=_instantiation_metadata.from_server, + path_to_item=property_path_to_item, + path_to_schemas=_instantiation_metadata.path_to_schemas, + ) + if _instantiation_metadata.from_server: + new_value = property_cls._from_openapi_data(value, _instantiation_metadata=prop_instantiation_metadata) + else: + new_value = property_cls(value, _instantiation_metadata=prop_instantiation_metadata) + 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)) + # print(('non-frozendict __getattr__', name)) + return super().__getattr__(self, name) + + def __getattribute__(self, name): + # print(('__getattribute__', 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, str, tuple, frozendict, FileIO, bytes} + + +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 + """ + + @staticmethod + def __get_simple_class(input_value): + """Returns an input_value's simple class that we will use for type checking + + Args: + input_value (class/class_instance): the item for which we will return + the simple class + """ + if isinstance(input_value, tuple): + return tuple + elif isinstance(input_value, frozendict): + return frozendict + elif isinstance(input_value, none_type): + return none_type + elif isinstance(input_value, bytes): + return bytes + elif isinstance(input_value, (io.FileIO, io.BufferedReader)): + return FileIO + 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, float): + return float + 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) + + @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 _class_by_base_class(cls, base_cls: type) -> type: + cls_name = "Dynamic"+cls.__name__ + if base_cls is bool: + new_cls = get_new_class(cls_name, (cls, BoolBase, BoolClass)) + elif base_cls is str: + new_cls = get_new_class(cls_name, (cls, StrBase, str)) + elif base_cls is Decimal: + new_cls = get_new_class(cls_name, (cls, NumberBase, Decimal)) + elif base_cls is tuple: + new_cls = get_new_class(cls_name, (cls, ListBase, tuple)) + elif base_cls is frozendict: + new_cls = get_new_class(cls_name, (cls, DictBase, frozendict)) + elif base_cls is none_type: + new_cls = get_new_class(cls_name, (cls, NoneBase, NoneClass)) + log_cache_usage(get_new_class) + return new_cls + + @classmethod + def _validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + 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/frozendict/tuple + 2. enum value cases: 'hi', 1 -> no base_class set because the enum includes the base class + 3. uninheritable type: True/False/None -> no base_class because the base class is not inheritable + _enum_by_value will handle this use case + + 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 + """ + arg = args[0] + + base_class = cls.__get_simple_class(arg) + failed_type_check_classes = cls._validate_type(base_class) + if failed_type_check_classes: + raise cls.__get_type_error( + arg, + _instantiation_metadata.path_to_item, + failed_type_check_classes, + key_type=False, + ) + if hasattr(cls, '_validate_validations_pass'): + cls._validate_validations_pass(arg, _instantiation_metadata) + path_to_schemas = defaultdict(set) + path_to_schemas[_instantiation_metadata.path_to_item].add(cls) + + if hasattr(cls, "_enum_by_value"): + cls._validate_enum_value(arg) + return path_to_schemas + + if base_class is none_type or base_class is bool: + return path_to_schemas + + path_to_schemas[_instantiation_metadata.path_to_item].add(base_class) + return path_to_schemas + + @classmethod + def _validate_enum_value(cls, arg): + try: + cls._enum_by_value[arg] + except KeyError: + raise ApiValueError("Invalid value {} passed in to {}, {}".format(arg, cls, cls._enum_value_to_name)) + + @classmethod + def __get_new_cls(cls, arg, _instantiation_metadata: InstantiationMetadata): + """ + PATH 1 - 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 + """ + if ( + _instantiation_metadata.path_to_schemas and + _instantiation_metadata.path_to_item in _instantiation_metadata.path_to_schemas): + chosen_new_cls = _instantiation_metadata.path_to_schemas[_instantiation_metadata.path_to_item] + # print('leaving __get_new_cls early for cls {} because path_to_schemas exists'.format(cls)) + # print(_instantiation_metadata.path_to_item) + # print(chosen_new_cls) + return chosen_new_cls + """ + 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 = cls._validate(arg, _instantiation_metadata=_instantiation_metadata) + from pprint import pprint + pprint(dict(_path_to_schemas)) + # loop through it make a new class for each entry + for path, schema_classes in _path_to_schemas.items(): + enum_schema = any( + hasattr(this_cls, '_enum_by_value') for this_cls in schema_classes) + inheritable_primitive_type = schema_classes.intersection(inheritable_primitive_types_set) + chosen_schema_classes = schema_classes + suffix = tuple() + if inheritable_primitive_type: + chosen_schema_classes = schema_classes - inheritable_primitive_types_set + if not enum_schema: + # include the inheritable_primitive_type + suffix = tuple(inheritable_primitive_type) + + if len(chosen_schema_classes) == 1 and not suffix: + mfg_cls = tuple(chosen_schema_classes)[0] + else: + x_schema = schema_descendents & chosen_schema_classes + if x_schema: + x_schema = x_schema.pop() + if any(c is not x_schema and issubclass(c, x_schema) for c in chosen_schema_classes): + # needed to not have a mro error in get_new_class + chosen_schema_classes.remove(x_schema) + 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) + + if inheritable_primitive_type and not enum_schema: + _instantiation_metadata.path_to_schemas[path] = mfg_cls + continue + + # Use case: value is None, True, False, or an enum value + # print('choosing enum class for path {} in arg {}'.format(path, arg)) + value = arg + for key in path[1:]: + value = value[key] + if hasattr(mfg_cls, '_enum_by_value'): + mfg_cls = mfg_cls._enum_by_value[value] + elif value in {True, False}: + mfg_cls = mfg_cls._class_by_base_class(bool) + elif value is None: + mfg_cls = mfg_cls._class_by_base_class(none_type) + else: + raise ApiValueError('Unhandled case value={} bases={}'.format(value, mfg_cls.__bases__)) + _instantiation_metadata.path_to_schemas[path] = mfg_cls + + return _instantiation_metadata.path_to_schemas[_instantiation_metadata.path_to_item] + + @classmethod + def __get_new_instance_without_conversion(cls, arg, _instantiation_metadata): + # PATH 2 - we have a Dynamic class and we are making an instance of it + if issubclass(cls, tuple): + items = cls._get_items(arg, _instantiation_metadata=_instantiation_metadata) + return super(Schema, cls).__new__(cls, items) + elif issubclass(cls, frozendict): + properties = cls._get_properties(arg, _instantiation_metadata=_instantiation_metadata) + return super(Schema, cls).__new__(cls, properties) + """ + str = openapi str, date, and datetime + 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, + bool, + None, + 'Schema', + dict, + frozendict, + tuple, + list, + io.FileIO, + io.BufferedReader, + bytes + ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] + ): + arg = cast_to_allowed_types(arg, from_server=True) + _instantiation_metadata = InstantiationMetadata(from_server=True) if _instantiation_metadata is None else _instantiation_metadata + if not _instantiation_metadata.from_server: + raise ApiValueError( + 'from_server must be True in this code path, if you need it to be False, use cls()' + ) + new_cls = cls.__get_new_cls(arg, _instantiation_metadata) + new_inst = new_cls.__get_new_instance_without_conversion(arg, _instantiation_metadata) + 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, float, int, str, date, datetime, bool, None, 'Schema'], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, **kwargs: typing.Union[dict, frozendict, list, tuple, Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset]): + """ + Schema __new__ + + Args: + args (int/float/Decimal/str/list/tuple/dict/frozendict/bool/None): the value + kwargs (str, int/float/Decimal/str/list/tuple/dict/frozendict/bool/None): dict values + _instantiation_metadata: contains the needed from_server, configuration, path_to_item + """ + 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) + _instantiation_metadata = InstantiationMetadata() if _instantiation_metadata is None else _instantiation_metadata + if _instantiation_metadata.from_server: + raise ApiValueError( + 'from_server must be False in this code path, if you need it to be True, use cls._from_openapi_data()' + ) + arg = cast_to_allowed_types(arg, from_server=_instantiation_metadata.from_server) + new_cls = cls.__get_new_cls(arg, _instantiation_metadata) + return new_cls.__get_new_instance_without_conversion(arg, _instantiation_metadata) + + def __init__( + self, + *args: typing.Union[ + dict, frozendict, list, tuple, Decimal, float, int, str, date, datetime, bool, None, 'Schema'], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Union[ + dict, frozendict, list, tuple, 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, int, float, None, dict, frozendict, list, tuple, bytes, Schema], from_server=False) -> typing.Union[str, bytes, int, float, None, frozendict, tuple, Schema]: + """ + from_server=False date, datetime -> str + int, float -> Decimal + StrSchema will convert that to bytes and remember the encoding when we pass in str input + """ + if isinstance(arg, (date, datetime)): + if not from_server: + return arg.isoformat() + # ApiTypeError will be thrown later by _validate_type + return arg + elif isinstance(arg, bool): + """ + this check must come before isinstance(arg, (int, float)) + because isinstance(True, int) is True + """ + return arg + elif isinstance(arg, Decimal): + return arg + elif isinstance(arg, int): + return Decimal(arg) + elif isinstance(arg, float): + decimal_from_float = Decimal(arg) + if decimal_from_float.as_integer_ratio()[1] == 1: + # 9.0 -> Decimal('9.0') + # 3.4028234663852886e+38 -> Decimal('340282346638528859811704183484516925440.0') + return Decimal(str(decimal_from_float)+'.0') + return decimal_from_float + elif isinstance(arg, str): + return arg + elif isinstance(arg, bytes): + return arg + elif isinstance(arg, (io.FileIO, io.BufferedReader)): + if arg.closed: + raise ApiValueError('Invalid file state; file is closed and must be open') + return arg + elif type(arg) is list or type(arg) is tuple: + return tuple([cast_to_allowed_types(item) for item in arg]) + elif type(arg) is dict or type(arg) is frozendict: + return frozendict({key: cast_to_allowed_types(val) for key, val in arg.items() if val is not unset}) + elif arg is None: + return arg + elif isinstance(arg, Schema): + return arg + raise ValueError('Invalid type passed in got input={} type={}'.format(arg, type(arg))) + + +class ComposedBase(Discriminable): + + @classmethod + def __get_allof_classes(cls, *args, _instantiation_metadata: InstantiationMetadata): + path_to_schemas = defaultdict(set) + for allof_cls in cls._composed_schemas['allOf']: + if allof_cls in _instantiation_metadata.base_classes: + continue + other_path_to_schemas = allof_cls._validate(*args, _instantiation_metadata=_instantiation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __get_oneof_class( + cls, + *args, + discriminated_cls, + _instantiation_metadata: InstantiationMetadata, + path_to_schemas: typing.Dict[typing.Tuple, typing.Set[typing.Type[Schema]]] + ): + oneof_classes = [] + chosen_oneof_cls = None + original_base_classes = _instantiation_metadata.base_classes + new_base_classes = _instantiation_metadata.base_classes + path_to_schemas = defaultdict(set) + for oneof_cls in cls._composed_schemas['oneOf']: + if oneof_cls in path_to_schemas[_instantiation_metadata.path_to_item]: + oneof_classes.append(oneof_cls) + continue + if isinstance(args[0], oneof_cls): + # passed in instance is the correct type + chosen_oneof_cls = oneof_cls + oneof_classes.append(oneof_cls) + continue + _instantiation_metadata.base_classes = original_base_classes + try: + path_to_schemas = oneof_cls._validate(*args, _instantiation_metadata=_instantiation_metadata) + new_base_classes = _instantiation_metadata.base_classes + except (ApiValueError, ApiTypeError) as ex: + if discriminated_cls is not None and oneof_cls is discriminated_cls: + raise ex + continue + chosen_oneof_cls = oneof_cls + 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) + ) + _instantiation_metadata.base_classes = new_base_classes + return path_to_schemas + + @classmethod + def __get_anyof_classes( + cls, + *args, + discriminated_cls, + _instantiation_metadata: InstantiationMetadata + ): + anyof_classes = [] + chosen_anyof_cls = None + original_base_classes = _instantiation_metadata.base_classes + path_to_schemas = defaultdict(set) + for anyof_cls in cls._composed_schemas['anyOf']: + if anyof_cls in _instantiation_metadata.base_classes: + continue + if isinstance(args[0], anyof_cls): + # passed in instance is the correct type + chosen_anyof_cls = anyof_cls + anyof_classes.append(anyof_cls) + continue + + _instantiation_metadata.base_classes = original_base_classes + try: + other_path_to_schemas = anyof_cls._validate(*args, _instantiation_metadata=_instantiation_metadata) + except (ApiValueError, ApiTypeError) as ex: + if discriminated_cls is not None and anyof_cls is discriminated_cls: + raise ex + continue + original_base_classes = _instantiation_metadata.base_classes + chosen_anyof_cls = anyof_cls + 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, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + 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 args and isinstance(args[0], Schema) and _instantiation_metadata.from_server is False: + if isinstance(args[0], 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(args[0]), + _instantiation_metadata.path_to_item + ) + ) + + # validation checking on types, validations, and enums + path_to_schemas = super()._validate(*args, _instantiation_metadata=_instantiation_metadata) + + _instantiation_metadata.base_classes |= frozenset({cls}) + + # process composed schema + _discriminator = getattr(cls, '_discriminator', None) + discriminated_cls = None + if _discriminator and args and isinstance(args[0], frozendict): + disc_property_name = list(_discriminator.keys())[0] + cls._ensure_discriminator_value_present(disc_property_name, _instantiation_metadata, *args) + # 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=args[0][disc_property_name]) + if discriminated_cls is None: + raise ApiValueError( + "Invalid discriminator value '{}' was passed in to {}.{} Only the values {} are allowed at {}".format( + args[0][disc_property_name], + cls.__name__, + disc_property_name, + list(_discriminator[disc_property_name].keys()), + _instantiation_metadata.path_to_item + (disc_property_name,) + ) + ) + + if cls._composed_schemas['allOf']: + other_path_to_schemas = cls.__get_allof_classes(*args, _instantiation_metadata=_instantiation_metadata) + update(path_to_schemas, other_path_to_schemas) + if cls._composed_schemas['oneOf']: + other_path_to_schemas = cls.__get_oneof_class( + *args, + discriminated_cls=discriminated_cls, + _instantiation_metadata=_instantiation_metadata, + 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( + *args, + discriminated_cls=discriminated_cls, + _instantiation_metadata=_instantiation_metadata + ) + update(path_to_schemas, other_path_to_schemas) + + if discriminated_cls is not None: + # TODO use an exception from this package here + assert discriminated_cls in path_to_schemas[_instantiation_metadata.path_to_item] + return path_to_schemas + + +# DictBase, ListBase, NumberBase, StrBase, BoolBase, NoneBase +class ComposedSchema( + _SchemaTypeChecker(typing.Union[none_type, str, Decimal, bool, tuple, frozendict]), + ComposedBase, + DictBase, + ListBase, + NumberBase, + StrBase, + BoolBase, + NoneBase, + Schema +): + + # subclass properties + _composed_schemas = {} + + @classmethod + def _from_openapi_data(cls, *args: typing.Any, _instantiation_metadata: typing.Optional[InstantiationMetadata] = 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], _instantiation_metadata=_instantiation_metadata) + + +class ListSchema( + _SchemaTypeChecker(typing.Union[tuple]), + ListBase, + Schema +): + + @classmethod + def _from_openapi_data(cls, arg: typing.List[typing.Any], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, arg: typing.Union[list, tuple], **kwargs: InstantiationMetadata): + return super().__new__(cls, arg, **kwargs) + + +class NoneSchema( + _SchemaTypeChecker(typing.Union[none_type]), + NoneBase, + Schema +): + + @classmethod + def _from_openapi_data(cls, arg: None, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, arg: None, **kwargs: typing.Union[InstantiationMetadata]): + return super().__new__(cls, arg, **kwargs) + + +class NumberSchema( + _SchemaTypeChecker(typing.Union[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], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, arg: typing.Union[Decimal, int, float], **kwargs: typing.Union[InstantiationMetadata]): + 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], _instantiation_metadata: InstantiationMetadata): + if isinstance(arg, Decimal): + exponent = arg.as_tuple().exponent + if exponent != 0: + raise ApiValueError( + "Invalid value '{}' for type integer at {}".format(arg, _instantiation_metadata.path_to_item) + ) + + @classmethod + def _validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + IntBase _validate + TODO what about types = (int, number) -> IntBase, NumberBase? We could drop int and keep number only + """ + cls._validate_format(args[0], _instantiation_metadata=_instantiation_metadata) + return super()._validate(*args, _instantiation_metadata=_instantiation_metadata) + + +class IntSchema(IntBase, NumberSchema): + + @classmethod + def _from_openapi_data(cls, arg: int, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, arg: typing.Union[Decimal, int], **kwargs: typing.Union[InstantiationMetadata]): + return super().__new__(cls, arg, **kwargs) + + +class Int32Schema( + _SchemaValidator( + inclusive_minimum=Decimal(-2147483648), + inclusive_maximum=Decimal(2147483647) + ), + IntSchema +): + pass + +class Int64Schema( + _SchemaValidator( + inclusive_minimum=Decimal(-9223372036854775808), + inclusive_maximum=Decimal(9223372036854775807) + ), + IntSchema +): + pass + + +class Float32Schema( + _SchemaValidator( + inclusive_minimum=Decimal(-3.4028234663852886e+38), + inclusive_maximum=Decimal(3.4028234663852886e+38) + ), + NumberSchema +): + + @classmethod + def _from_openapi_data(cls, arg: typing.Union[float, Decimal], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + # todo check format + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + +class Float64Schema( + _SchemaValidator( + inclusive_minimum=Decimal(-1.7976931348623157E+308), + inclusive_maximum=Decimal(1.7976931348623157E+308) + ), + NumberSchema +): + + @classmethod + def _from_openapi_data(cls, arg: typing.Union[float, Decimal], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + # todo check format + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + +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], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None) -> 'StrSchema': + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, arg: typing.Union[str, date, datetime], **kwargs: typing.Union[InstantiationMetadata]): + return super().__new__(cls, arg, **kwargs) + + +class DateSchema(DateBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, datetime], **kwargs: typing.Union[InstantiationMetadata]): + return super().__new__(cls, arg, **kwargs) + + +class DateTimeSchema(DateTimeBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, datetime], **kwargs: typing.Union[InstantiationMetadata]): + 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[InstantiationMetadata]): + 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[InstantiationMetadata]): + 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': [ + ], + } + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader, bytes], **kwargs: typing.Union[InstantiationMetadata]): + return super().__new__(cls, arg) + + +class BoolSchema( + _SchemaTypeChecker(typing.Union[bool]), + BoolBase, + Schema +): + + @classmethod + def _from_openapi_data(cls, arg: bool, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, arg: bool, **kwargs: typing.Union[InstantiationMetadata]): + return super().__new__(cls, arg, **kwargs) + + +class AnyTypeSchema( + _SchemaTypeChecker( + typing.Union[frozendict, tuple, Decimal, str, bool, none_type, 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], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, *args: typing.Union[dict, frozendict], **kwargs: typing.Union[dict, frozendict, list, tuple, Decimal, float, int, str, date, datetime, bool, None, bytes, Schema, Unset, InstantiationMetadata]): + return super().__new__(cls, *args, **kwargs) + + +schema_descendents = 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-experimental/setup.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/setup.handlebars new file mode 100644 index 000000000000..476157a0c5d2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/setup.handlebars @@ -0,0 +1,51 @@ +# coding: utf-8 + +{{>partial_header}} + +from setuptools import setup, find_packages # noqa: H301 + +NAME = "{{{projectName}}}" +VERSION = "{{packageVersion}}" +{{#with apiInfo}} +# 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", +{{#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}} +] + +setup( + name=NAME, + version=VERSION, + description="{{appName}}", + author="{{#if infoName}}{{infoName}}{{/if}}{{#unless infoName}}OpenAPI Generator community{{/unless}}", + author_email="{{#if infoEmail}}{{infoEmail}}{{/if}}{{#unless infoEmail}}team@openapitools.org{{/unless}}", + url="{{packageUrl}}", + keywords=["OpenAPI", "OpenAPI-Generator", "{{{appName}}}"], + python_requires=">=3.9", + install_requires=REQUIRES, + packages=find_packages(exclude=["test", "tests"]), + include_package_data=True, + {{#if licenseInfo}}license="{{licenseInfo}}", + {{/if}}long_description="""\ + {{appDescription}} # noqa: E501 + """ +) +{{/with}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/setup_cfg.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/setup_cfg.handlebars new file mode 100644 index 000000000000..8cb28d8c2852 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/setup_cfg.handlebars @@ -0,0 +1,13 @@ +{{#if useNose}} +[nosetests] +logging-clear-handlers=true +verbosity=2 +randomize=true +exe=true +with-coverage=true +cover-package={{{packageName}}} +cover-erase=true + +{{/if}} +[flake8] +max-line-length=99 diff --git a/modules/openapi-generator/src/main/resources/python-experimental/signing.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/signing.handlebars new file mode 100644 index 000000000000..26d2b8cb37c9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/signing.handlebars @@ -0,0 +1,409 @@ +# coding: utf-8 +{{>partial_header}} + +from base64 import b64encode +from Crypto.IO import PEM, PKCS8 +from Crypto.Hash import SHA256, SHA512 +from Crypto.PublicKey import RSA, ECC +from Crypto.Signature import PKCS1_v1_5, pss, DSS +from email.utils import formatdate +import json +import os +import re +from time import time +from urllib.parse import urlencode, urlparse + +# The constants below define a subset of HTTP headers that can be included in the +# HTTP signature scheme. Additional headers may be included in the signature. + +# The '(request-target)' header is a calculated field that includes the HTTP verb, +# the URL path and the URL query. +HEADER_REQUEST_TARGET = '(request-target)' +# The time when the HTTP signature was generated. +HEADER_CREATED = '(created)' +# The time when the HTTP signature expires. The API server should reject HTTP requests +# that have expired. +HEADER_EXPIRES = '(expires)' +# The 'Host' header. +HEADER_HOST = 'Host' +# The 'Date' header. +HEADER_DATE = 'Date' +# When the 'Digest' header is included in the HTTP signature, the client automatically +# computes the digest of the HTTP request body, per RFC 3230. +HEADER_DIGEST = 'Digest' +# The 'Authorization' header is automatically generated by the client. It includes +# the list of signed headers and a base64-encoded signature. +HEADER_AUTHORIZATION = 'Authorization' + +# The constants below define the cryptographic schemes for the HTTP signature scheme. +SCHEME_HS2019 = 'hs2019' +SCHEME_RSA_SHA256 = 'rsa-sha256' +SCHEME_RSA_SHA512 = 'rsa-sha512' + +# The constants below define the signature algorithms that can be used for the HTTP +# signature scheme. +ALGORITHM_RSASSA_PSS = 'RSASSA-PSS' +ALGORITHM_RSASSA_PKCS1v15 = 'RSASSA-PKCS1-v1_5' + +ALGORITHM_ECDSA_MODE_FIPS_186_3 = 'fips-186-3' +ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979 = 'deterministic-rfc6979' +ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS = { + ALGORITHM_ECDSA_MODE_FIPS_186_3, + ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979 +} + +# The cryptographic hash algorithm for the message signature. +HASH_SHA256 = 'sha256' +HASH_SHA512 = 'sha512' + + +class HttpSigningConfiguration(object): + """The configuration parameters for the HTTP signature security scheme. + The HTTP signature security scheme is used to sign HTTP requests with a private key + which is in possession of the API client. + An 'Authorization' header is calculated by creating a hash of select headers, + and optionally the body of the HTTP request, then signing the hash value using + a private key. The 'Authorization' header is added to outbound HTTP requests. + + NOTE: This class is auto generated by OpenAPI Generator + + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param key_id: A string value specifying the identifier of the cryptographic key, + when signing HTTP requests. + :param signing_scheme: A string value specifying the signature scheme, when + signing HTTP requests. + Supported value are hs2019, rsa-sha256, rsa-sha512. + Avoid using rsa-sha256, rsa-sha512 as they are deprecated. These values are + available for server-side applications that only support the older + HTTP signature algorithms. + :param private_key_path: A string value specifying the path of the file containing + a private key. The private key is used to sign HTTP requests. + :param private_key_passphrase: A string value specifying the passphrase to decrypt + the private key. + :param signed_headers: A list of strings. Each value is the name of a HTTP header + that must be included in the HTTP signature calculation. + The two special signature headers '(request-target)' and '(created)' SHOULD be + included in SignedHeaders. + The '(created)' header expresses when the signature was created. + The '(request-target)' header is a concatenation of the lowercased :method, an + ASCII space, and the :path pseudo-headers. + When signed_headers is not specified, the client defaults to a single value, + '(created)', in the list of HTTP headers. + When SignedHeaders contains the 'Digest' value, the client performs the + following operations: + 1. Calculate a digest of request body, as specified in RFC3230, section 4.3.2. + 2. Set the 'Digest' header in the request body. + 3. Include the 'Digest' header and value in the HTTP signature. + :param signing_algorithm: A string value specifying the signature algorithm, when + signing HTTP requests. + Supported values are: + 1. For RSA keys: RSASSA-PSS, RSASSA-PKCS1-v1_5. + 2. For ECDSA keys: fips-186-3, deterministic-rfc6979. + If None, the signing algorithm is inferred from the private key. + The default signing algorithm for RSA keys is RSASSA-PSS. + The default signing algorithm for ECDSA keys is fips-186-3. + :param hash_algorithm: The hash algorithm for the signature. Supported values are + sha256 and sha512. + If the signing_scheme is rsa-sha256, the hash algorithm must be set + to None or sha256. + If the signing_scheme is rsa-sha512, the hash algorithm must be set + to None or sha512. + :param signature_max_validity: The signature max validity, expressed as + a datetime.timedelta value. It must be a positive value. + """ + def __init__(self, key_id, signing_scheme, private_key_path, + private_key_passphrase=None, + signed_headers=None, + signing_algorithm=None, + hash_algorithm=None, + signature_max_validity=None): + self.key_id = key_id + if signing_scheme not in {SCHEME_HS2019, SCHEME_RSA_SHA256, SCHEME_RSA_SHA512}: + raise Exception("Unsupported security scheme: {0}".format(signing_scheme)) + self.signing_scheme = signing_scheme + if not os.path.exists(private_key_path): + raise Exception("Private key file does not exist") + self.private_key_path = private_key_path + self.private_key_passphrase = private_key_passphrase + self.signing_algorithm = signing_algorithm + self.hash_algorithm = hash_algorithm + if signing_scheme == SCHEME_RSA_SHA256: + if self.hash_algorithm is None: + self.hash_algorithm = HASH_SHA256 + elif self.hash_algorithm != HASH_SHA256: + raise Exception("Hash algorithm must be sha256 when security scheme is %s" % + SCHEME_RSA_SHA256) + elif signing_scheme == SCHEME_RSA_SHA512: + if self.hash_algorithm is None: + self.hash_algorithm = HASH_SHA512 + elif self.hash_algorithm != HASH_SHA512: + raise Exception("Hash algorithm must be sha512 when security scheme is %s" % + SCHEME_RSA_SHA512) + elif signing_scheme == SCHEME_HS2019: + if self.hash_algorithm is None: + self.hash_algorithm = HASH_SHA256 + elif self.hash_algorithm not in {HASH_SHA256, HASH_SHA512}: + raise Exception("Invalid hash algorithm") + if signature_max_validity is not None and signature_max_validity.total_seconds() < 0: + raise Exception("The signature max validity must be a positive value") + self.signature_max_validity = signature_max_validity + # If the user has not provided any signed_headers, the default must be set to '(created)', + # as specified in the 'HTTP signature' standard. + if signed_headers is None or len(signed_headers) == 0: + signed_headers = [HEADER_CREATED] + if self.signature_max_validity is None and HEADER_EXPIRES in signed_headers: + raise Exception( + "Signature max validity must be set when " + "'(expires)' signature parameter is specified") + if len(signed_headers) != len(set(signed_headers)): + raise Exception("Cannot have duplicates in the signed_headers parameter") + if HEADER_AUTHORIZATION in signed_headers: + raise Exception("'Authorization' header cannot be included in signed headers") + self.signed_headers = signed_headers + self.private_key = None + """The private key used to sign HTTP requests. + Initialized when the PEM-encoded private key is loaded from a file. + """ + self.host = None + """The host name, optionally followed by a colon and TCP port number. + """ + self._load_private_key() + + def get_http_signature_headers(self, resource_path, method, headers, body, query_params): + """Create a cryptographic message signature for the HTTP request and add the signed headers. + + :param resource_path : A string representation of the HTTP request resource path. + :param method: A string representation of the HTTP request method, e.g. GET, POST. + :param headers: A dict containing the HTTP request headers. + :param body: The object representing the HTTP request body. + :param query_params: A string representing the HTTP request query parameters. + :return: A dict of HTTP headers that must be added to the outbound HTTP request. + """ + if method is None: + raise Exception("HTTP method must be set") + if resource_path is None: + raise Exception("Resource path must be set") + + signed_headers_list, request_headers_dict = self._get_signed_header_info( + resource_path, method, headers, body, query_params) + + header_items = [ + "{0}: {1}".format(key.lower(), value) for key, value in signed_headers_list] + string_to_sign = "\n".join(header_items) + + digest, digest_prefix = self._get_message_digest(string_to_sign.encode()) + b64_signed_msg = self._sign_digest(digest) + + request_headers_dict[HEADER_AUTHORIZATION] = self._get_authorization_header( + signed_headers_list, b64_signed_msg) + + return request_headers_dict + + def get_public_key(self): + """Returns the public key object associated with the private key. + """ + pubkey = None + if isinstance(self.private_key, RSA.RsaKey): + pubkey = self.private_key.publickey() + elif isinstance(self.private_key, ECC.EccKey): + pubkey = self.private_key.public_key() + return pubkey + + def _load_private_key(self): + """Load the private key used to sign HTTP requests. + The private key is used to sign HTTP requests as defined in + https://datatracker.ietf.org/doc/draft-cavage-http-signatures/. + """ + if self.private_key is not None: + return + with open(self.private_key_path, 'r') as f: + pem_data = f.read() + # Verify PEM Pre-Encapsulation Boundary + r = re.compile(r"\s*-----BEGIN (.*)-----\s+") + m = r.match(pem_data) + if not m: + raise ValueError("Not a valid PEM pre boundary") + pem_header = m.group(1) + if pem_header == 'RSA PRIVATE KEY': + self.private_key = RSA.importKey(pem_data, self.private_key_passphrase) + elif pem_header == 'EC PRIVATE KEY': + self.private_key = ECC.import_key(pem_data, self.private_key_passphrase) + elif pem_header in {'PRIVATE KEY', 'ENCRYPTED PRIVATE KEY'}: + # Key is in PKCS8 format, which is capable of holding many different + # types of private keys, not just EC keys. + (key_binary, pem_header, is_encrypted) = \ + PEM.decode(pem_data, self.private_key_passphrase) + (oid, privkey, params) = \ + PKCS8.unwrap(key_binary, passphrase=self.private_key_passphrase) + if oid == '1.2.840.10045.2.1': + self.private_key = ECC.import_key(pem_data, self.private_key_passphrase) + else: + raise Exception("Unsupported key: {0}. OID: {1}".format(pem_header, oid)) + else: + raise Exception("Unsupported key: {0}".format(pem_header)) + # Validate the specified signature algorithm is compatible with the private key. + if self.signing_algorithm is not None: + supported_algs = None + if isinstance(self.private_key, RSA.RsaKey): + supported_algs = {ALGORITHM_RSASSA_PSS, ALGORITHM_RSASSA_PKCS1v15} + elif isinstance(self.private_key, ECC.EccKey): + supported_algs = ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS + if supported_algs is not None and self.signing_algorithm not in supported_algs: + raise Exception( + "Signing algorithm {0} is not compatible with private key".format( + self.signing_algorithm)) + + def _get_signed_header_info(self, resource_path, method, headers, body, query_params): + """Build the HTTP headers (name, value) that need to be included in + the HTTP signature scheme. + + :param resource_path : A string representation of the HTTP request resource path. + :param method: A string representation of the HTTP request method, e.g. GET, POST. + :param headers: A dict containing the HTTP request headers. + :param body: The object (e.g. a dict) representing the HTTP request body. + :param query_params: A string representing the HTTP request query parameters. + :return: A tuple containing two dict objects: + The first dict contains the HTTP headers that are used to calculate + the HTTP signature. + The second dict contains the HTTP headers that must be added to + the outbound HTTP request. + """ + + if body is None: + body = '' + else: + body = json.dumps(body) + + # Build the '(request-target)' HTTP signature parameter. + target_host = urlparse(self.host).netloc + target_path = urlparse(self.host).path + request_target = method.lower() + " " + target_path + resource_path + if query_params: + request_target += "?" + urlencode(query_params) + + # Get UNIX time, e.g. seconds since epoch, not including leap seconds. + now = time() + # Format date per RFC 7231 section-7.1.1.2. An example is: + # Date: Wed, 21 Oct 2015 07:28:00 GMT + cdate = formatdate(timeval=now, localtime=False, usegmt=True) + # The '(created)' value MUST be a Unix timestamp integer value. + # Subsecond precision is not supported. + created = int(now) + if self.signature_max_validity is not None: + expires = now + self.signature_max_validity.total_seconds() + + signed_headers_list = [] + request_headers_dict = {} + for hdr_key in self.signed_headers: + hdr_key = hdr_key.lower() + if hdr_key == HEADER_REQUEST_TARGET: + value = request_target + elif hdr_key == HEADER_CREATED: + value = '{0}'.format(created) + elif hdr_key == HEADER_EXPIRES: + value = '{0}'.format(expires) + elif hdr_key == HEADER_DATE.lower(): + value = cdate + request_headers_dict[HEADER_DATE] = '{0}'.format(cdate) + elif hdr_key == HEADER_DIGEST.lower(): + request_body = body.encode() + body_digest, digest_prefix = self._get_message_digest(request_body) + b64_body_digest = b64encode(body_digest.digest()) + value = digest_prefix + b64_body_digest.decode('ascii') + request_headers_dict[HEADER_DIGEST] = '{0}{1}'.format( + digest_prefix, b64_body_digest.decode('ascii')) + elif hdr_key == HEADER_HOST.lower(): + value = target_host + request_headers_dict[HEADER_HOST] = '{0}'.format(target_host) + else: + value = next((v for k, v in headers.items() if k.lower() == hdr_key), None) + if value is None: + raise Exception( + "Cannot sign HTTP request. " + "Request does not contain the '{0}' header".format(hdr_key)) + signed_headers_list.append((hdr_key, value)) + + return signed_headers_list, request_headers_dict + + def _get_message_digest(self, data): + """Calculates and returns a cryptographic digest of a specified HTTP request. + + :param data: The string representation of the date to be hashed with a cryptographic hash. + :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 + to generate the 'Digest' header as specified in RFC 3230. + """ + if self.hash_algorithm == HASH_SHA512: + digest = SHA512.new() + prefix = 'SHA-512=' + elif self.hash_algorithm == HASH_SHA256: + digest = SHA256.new() + prefix = 'SHA-256=' + else: + raise Exception("Unsupported hash algorithm: {0}".format(self.hash_algorithm)) + digest.update(data) + return digest, prefix + + def _sign_digest(self, digest): + """Signs a message digest with a private key specified in the signing_info. + + :param digest: A hashing object that contains the cryptographic digest of the HTTP request. + :return: A base-64 string representing the cryptographic signature of the input digest. + """ + sig_alg = self.signing_algorithm + if isinstance(self.private_key, RSA.RsaKey): + if sig_alg is None or sig_alg == ALGORITHM_RSASSA_PSS: + # RSASSA-PSS in Section 8.1 of RFC8017. + signature = pss.new(self.private_key).sign(digest) + elif sig_alg == ALGORITHM_RSASSA_PKCS1v15: + # RSASSA-PKCS1-v1_5 in Section 8.2 of RFC8017. + signature = PKCS1_v1_5.new(self.private_key).sign(digest) + else: + raise Exception("Unsupported signature algorithm: {0}".format(sig_alg)) + elif isinstance(self.private_key, ECC.EccKey): + if sig_alg is None: + sig_alg = ALGORITHM_ECDSA_MODE_FIPS_186_3 + if sig_alg in ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS: + # draft-ietf-httpbis-message-signatures-00 does not specify the ECDSA encoding. + # Issue: https://github.com/w3c-ccg/http-signatures/issues/107 + signature = DSS.new(key=self.private_key, mode=sig_alg, + encoding='der').sign(digest) + else: + raise Exception("Unsupported signature algorithm: {0}".format(sig_alg)) + else: + raise Exception("Unsupported private key: {0}".format(type(self.private_key))) + return b64encode(signature) + + def _get_authorization_header(self, signed_headers, signed_msg): + """Calculates and returns the value of the 'Authorization' header when signing HTTP requests. + + :param signed_headers : A list of tuples. Each value is the name of a HTTP header that + must be included in the HTTP signature calculation. + :param signed_msg: A base-64 encoded string representation of the signature. + :return: The string value of the 'Authorization' header, representing the signature + of the HTTP request. + """ + created_ts = None + expires_ts = None + for k, v in signed_headers: + if k == HEADER_CREATED: + created_ts = v + elif k == HEADER_EXPIRES: + expires_ts = v + lower_keys = [k.lower() for k, v in signed_headers] + headers_value = " ".join(lower_keys) + + auth_str = "Signature keyId=\"{0}\",algorithm=\"{1}\",".format( + self.key_id, self.signing_scheme) + if created_ts is not None: + auth_str = auth_str + "created={0},".format(created_ts) + if expires_ts is not None: + auth_str = auth_str + "expires={0},".format(expires_ts) + auth_str = auth_str + "headers=\"{0}\",signature=\"{1}\"".format( + headers_value, signed_msg.decode('ascii')) + + return auth_str diff --git a/modules/openapi-generator/src/main/resources/python-experimental/test-requirements.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/test-requirements.handlebars new file mode 100644 index 000000000000..3529726b16d4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/test-requirements.handlebars @@ -0,0 +1,15 @@ +{{#if useNose}} +coverage>=4.0.3 +nose>=1.3.7 +pluggy>=0.3.1 +py>=1.4.31 +randomize>=0.13 +{{/if}} +{{#unless useNose}} +pytest~=4.6.7 # needed for python 3.4 +pytest-cov>=2.8.1 +pytest-randomly==1.2.3 # needed for python 3.4 +{{/unless}} +{{#if hasHttpSignatureMethods}} +pycryptodome>=3.9.0 +{{/if}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-experimental/tox.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/tox.handlebars new file mode 100644 index 000000000000..5af8eb6f8315 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/tox.handlebars @@ -0,0 +1,9 @@ +[tox] +envlist = py3 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + {{#unless useNose}}pytest --cov={{{packageName}}}{{/unless}}{{#if useNose}}nosetests{{/if}} diff --git a/modules/openapi-generator/src/main/resources/python-experimental/travis.handlebars b/modules/openapi-generator/src/main/resources/python-experimental/travis.handlebars new file mode 100644 index 000000000000..5e4e1f0cc097 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-experimental/travis.handlebars @@ -0,0 +1,18 @@ +# 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 +{{#if useNose}} +script: nosetests +{{/if}} +{{#unless useNose}} +script: pytest --cov={{{packageName}}} +{{/unless}} 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-experimental/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml new file mode 100644 index 000000000000..f149e72a898d --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/python-experimental/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -0,0 +1,2655 @@ +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: " + \ + 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: + /foo: + get: + responses: + default: + description: response + content: + application/json: + schema: + type: object + properties: + string: + $ref: '#/components/schemas/Foo' + /pet: + servers: + - url: 'http://petstore.swagger.io/v2' + - url: 'http://path-server-test.petstore.local/v2' + post: + tags: + - pet + summary: Add a new pet to the store + description: Add a new pet to the store + operationId: addPet + responses: + '200': + description: Ok + '405': + description: Invalid input + security: + - http_signature_test: [] + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + 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' + 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 + 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: + - http_signature_test: [] + - petstore_auth: + - 'write:pets' + - '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: + - http_signature_test: [] + - petstore_auth: + - 'write:pets' + - '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: 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: + - 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/{order_id}': + 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: order_id + 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: order_id + 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 + 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 + 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 + 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 + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + 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 + '/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 + 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 + /fake_classname_test: + patch: + tags: + - 'fake_classname_tags 123#$%^' + summary: To test class name in snake case + description: To test class name in snake case + operationId: Classname + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + security: + - api_key_query: [] + requestBody: + $ref: '#/components/requestBodies/Client' + /fake: + patch: + tags: + - fake + summary: To test "client" model + description: To test "client" model + operationId: ClientModel + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + requestBody: + $ref: '#/components/requestBodies/Client' + get: + tags: + - fake + summary: To test enum parameters + description: To test enum parameters + operationId: EnumParameters + parameters: + - name: enum_header_string_array + in: header + description: Header parameter enum test (string array) + schema: + type: array + items: + type: string + default: $ + enum: + - '>' + - $ + - name: enum_header_string + in: header + description: Header parameter enum test (string) + schema: + type: string + enum: + - _abc + - '-efg' + - (xyz) + default: '-efg' + - name: enum_query_string_array + in: query + description: Query parameter enum test (string array) + schema: + type: array + items: + type: string + default: $ + enum: + - '>' + - $ + - name: enum_query_string + in: query + description: Query parameter enum test (string) + schema: + type: string + enum: + - _abc + - '-efg' + - (xyz) + default: '-efg' + - name: enum_query_integer + in: query + description: Query parameter enum test (double) + schema: + type: integer + format: int32 + enum: + - 1 + - -2 + - name: enum_query_double + in: query + description: Query parameter enum test (double) + schema: + type: number + format: double + enum: + - 1.1 + - -1.2 + responses: + '400': + description: Invalid request + '404': + description: Not found + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + enum_form_string_array: + description: Form parameter enum test (string array) + type: array + items: + type: string + default: $ + enum: + - '>' + - $ + enum_form_string: + description: Form parameter enum test (string) + type: string + enum: + - _abc + - '-efg' + - (xyz) + default: '-efg' + post: + tags: + - fake + summary: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + description: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + operationId: EndpointParameters + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - http_basic_test: [] + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + integer: + description: None + type: integer + minimum: 10 + maximum: 100 + int32: + description: None + type: integer + format: int32 + minimum: 20 + maximum: 200 + int64: + description: None + type: integer + format: int64 + number: + description: None + type: number + minimum: 32.1 + maximum: 543.2 + float: + description: None + type: number + format: float + maximum: 987.6 + double: + description: None + type: number + format: double + minimum: 67.8 + maximum: 123.4 + string: + description: None + type: string + pattern: '/[a-z]/i' + pattern_without_delimiter: + description: None + type: string + pattern: '^[A-Z].*' + byte: + description: None + type: string + format: byte + binary: + description: None + type: string + format: binary + date: + description: None + type: string + format: date + dateTime: + description: None + type: string + format: date-time + default: '2010-02-01T10:20:10.11111+01:00' + example: '2020-02-02T20:20:20.22222Z' + password: + description: None + type: string + format: password + minLength: 10 + maxLength: 64 + callback: + description: None + type: string + required: + - number + - double + - pattern_without_delimiter + - byte + delete: + tags: + - fake + security: + - bearer_test: [] + summary: Fake endpoint to test group parameters (optional) + description: Fake endpoint to test group parameters (optional) + operationId: GroupParameters + x-group-parameters: true + parameters: + - name: required_string_group + in: query + description: Required String in group parameters + required: true + schema: + type: integer + - name: required_boolean_group + in: header + description: Required Boolean in group parameters + required: true + schema: + type: boolean + - name: required_int64_group + in: query + description: Required Integer in group parameters + required: true + schema: + type: integer + format: int64 + - name: string_group + in: query + description: String in group parameters + schema: + type: integer + - name: boolean_group + in: header + description: Boolean in group parameters + schema: + type: boolean + - name: int64_group + in: query + description: Integer in group parameters + schema: + type: integer + format: int64 + responses: + '400': + description: Someting wrong + /fake/refs/number: + post: + tags: + - fake + description: Test serialization of outer number types + operationId: NumberWithValidations + requestBody: + description: Input number as post body + content: + application/json: + schema: + $ref: '#/components/schemas/NumberWithValidations' + required: false + responses: + '200': + description: Output number + content: + application/json: + schema: + $ref: '#/components/schemas/NumberWithValidations' + /fake/refs/mammal: + post: + tags: + - fake + description: Test serialization of mammals + operationId: Mammal + requestBody: + description: Input mammal + content: + application/json: + schema: + $ref: '#/components/schemas/mammal' + required: true + responses: + '200': + description: Output mammal + content: + application/json: + schema: + $ref: '#/components/schemas/mammal' + /fake/refs/string: + post: + tags: + - fake + description: Test serialization of outer string types + operationId: String + requestBody: + description: Input string as post body + content: + application/json: + schema: + $ref: '#/components/schemas/String' + required: false + responses: + '200': + description: Output string + content: + application/json: + schema: + $ref: '#/components/schemas/String' + x-codegen-request-body-name: body + /fake/refs/boolean: + post: + tags: + - fake + description: Test serialization of outer boolean types + operationId: Boolean + requestBody: + description: Input boolean as post body + content: + application/json: + schema: + $ref: '#/components/schemas/Boolean' + required: false + responses: + '200': + description: Output boolean + content: + application/json: + schema: + $ref: '#/components/schemas/Boolean' + x-codegen-request-body-name: body + /fake/refs/arraymodel: + post: + tags: + - fake + description: Test serialization of ArrayModel + operationId: ArrayModel + requestBody: + description: Input model + content: + application/json: + schema: + $ref: '#/components/schemas/AnimalFarm' + required: false + responses: + '200': + description: Output model + content: + application/json: + schema: + $ref: '#/components/schemas/AnimalFarm' + x-codegen-request-body-name: body + /fake/refs/composed_one_of_number_with_validations: + post: + tags: + - fake + description: Test serialization of object with $refed properties + operationId: ComposedOneOfDifferentTypes + requestBody: + description: Input model + content: + application/json: + schema: + $ref: '#/components/schemas/ComposedOneOfDifferentTypes' + required: false + responses: + '200': + description: Output model + content: + application/json: + schema: + $ref: '#/components/schemas/ComposedOneOfDifferentTypes' + /fake/refs/object_model_with_ref_props: + post: + tags: + - fake + description: Test serialization of object with $refed properties + operationId: ObjectModelWithRefProps + requestBody: + description: Input model + content: + application/json: + schema: + $ref: '#/components/schemas/ObjectModelWithRefProps' + required: false + responses: + '200': + description: Output model + content: + application/json: + schema: + $ref: '#/components/schemas/ObjectModelWithRefProps' + x-codegen-request-body-name: body + /fake/refs/enum: + post: + tags: + - fake + description: Test serialization of outer enum + operationId: StringEnum + requestBody: + description: Input enum + content: + application/json: + schema: + $ref: '#/components/schemas/StringEnum' + required: false + responses: + '200': + description: Output enum + content: + application/json: + schema: + $ref: '#/components/schemas/StringEnum' + x-codegen-request-body-name: body + /fake/refs/array-of-enums: + post: + tags: + - fake + summary: Array of Enums + operationId: ArrayOfEnums + requestBody: + description: Input enum + content: + application/json: + schema: + $ref: '#/components/schemas/ArrayOfEnums' + required: false + responses: + 200: + description: Got named array of enums + content: + application/json: + schema: + $ref: '#/components/schemas/ArrayOfEnums' + /fake/additional-properties-with-array-of-enums: + get: + tags: + - fake + summary: Additional Properties with Array of Enums + operationId: AdditionalPropertiesWithArrayOfEnums + requestBody: + description: Input enum + content: + application/json: + schema: + $ref: '#/components/schemas/AdditionalPropertiesWithArrayOfEnums' + required: false + responses: + 200: + description: Got object with additional properties with array of enums + content: + application/json: + schema: + $ref: '#/components/schemas/AdditionalPropertiesWithArrayOfEnums' + /fake/jsonFormData: + get: + tags: + - fake + summary: test json serialization of form data + description: '' + operationId: JsonFormData + responses: + '200': + description: successful operation + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + param: + description: field1 + type: string + param2: + description: field2 + type: string + required: + - param + - param2 + /fake/inline-additionalProperties: + post: + tags: + - fake + summary: test inline additionalProperties + description: '' + operationId: InlineAdditionalProperties + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + type: object + additionalProperties: + type: string + description: request body + required: true + /fake/body-with-query-params: + put: + tags: + - fake + operationId: BodyWithQueryParams + parameters: + - name: query + in: query + required: true + schema: + type: string + responses: + '200': + description: Success + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + required: true + /another-fake/dummy: + patch: + tags: + - $another-fake? + summary: To test special tags + description: To test special tags and operation ID starting with number + operationId: '123_test_@#$%_special_tags' + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + requestBody: + $ref: '#/components/requestBodies/Client' + /fake/body-with-file-schema: + put: + tags: + - fake + description: >- + For this test, the body for this request much reference a schema named + `File`. + operationId: BodyWithFileSchema + responses: + '200': + description: Success + requestBody: + content: + application/json: + 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: + put: + tags: + - fake + description: To test the collection format in query parameters + operationId: QueryParameterCollectionFormat + parameters: + - name: pipe + in: query + required: true + schema: + type: array + items: + type: string + - name: ioutil + in: query + required: true + style: form + explode: false + schema: + type: array + items: + type: string + - name: http + in: query + required: true + style: spaceDelimited + schema: + type: array + items: + type: string + - name: url + in: query + required: true + style: form + explode: false + schema: + type: array + items: + type: string + - name: context + in: query + required: true + explode: true + schema: + 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: + tags: + - fake + summary: parameter collision case + operationId: parameterCollisions + 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 + in: path + 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 + content: + application/json: + schema: {} + /fake/uploadFile: + post: + tags: + - fake + summary: uploads a file using multipart/form-data + description: '' + operationId: uploadFile + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + 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 + required: + - file + /fake/uploadFiles: + post: + tags: + - fake + summary: uploads files using multipart/form-data + description: '' + operationId: uploadFiles + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + files: + type: array + items: + type: string + format: binary + /fake/uploadDownloadFile: + post: + tags: + - fake + summary: uploads a file and downloads a file using application/octet-stream + description: '' + operationId: uploadDownloadFile + responses: + '200': + description: successful operation + content: + application/octet-stream: + schema: + type: string + format: binary + description: file to download + requestBody: + required: true + content: + application/octet-stream: + schema: + type: string + format: binary + description: file to upload + /fake/health: + get: + tags: + - fake + summary: Health check endpoint + responses: + 200: + description: The instance started successfully + content: + application/json: + schema: + $ref: '#/components/schemas/HealthCheckResult' +servers: + - url: 'http://{server}.swagger.io:{port}/v2' + description: petstore server + variables: + server: + enum: + - 'petstore' + - 'qa-petstore' + - 'dev-petstore' + default: 'petstore' + port: + enum: + - 80 + - 8080 + default: 80 + - url: https://localhost:8080/{version} + description: The local server + variables: + version: + enum: + - 'v1' + - 'v2' + default: 'v2' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + 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 + 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 + api_key_query: + type: apiKey + name: api_key_query + in: query + http_basic_test: + type: http + scheme: basic + bearer_test: + type: http + scheme: bearer + bearerFormat: JWT + http_signature_test: + # Test the 'HTTP signature' security scheme. + # Each HTTP request is cryptographically signed as specified + # in https://datatracker.ietf.org/doc/draft-cavage-http-signatures/ + type: http + scheme: signature + schemas: + Foo: + type: object + properties: + bar: + $ref: '#/components/schemas/Bar' + Bar: + type: string + default: bar + Order: + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + example: '2020-02-02T20:20:20.000222Z' + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + type: object + required: + - name + properties: + id: + type: integer + format: int64 + name: + type: string + default: default-name + xml: + name: Category + User: + type: object + properties: + id: + type: integer + format: int64 + x-is-unique: true + 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 + objectWithNoDeclaredProps: + type: object + # Note: the 'additionalProperties' keyword is not specified, which is + # equivalent to allowing undeclared properties of any type. + description: test code generation for objects + Value must be a map of strings to values. It cannot be the 'null' value. + objectWithNoDeclaredPropsNullable: + type: object + # Note: the 'additionalProperties' keyword is not specified, which is + # equivalent to allowing undeclared properties of any type. + description: test code generation for nullable objects. + Value must be a map of strings to values or the 'null' value. + nullable: true + 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 + # 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, + including the null value, string, number, boolean, array or object. + The 'nullable' attribute does not change the allowed values. + nullable: true + xml: + name: User + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + type: object + description: Pet object that needs to be added to the store + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + x-is-unique: true + 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: + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + Return: + description: Model for testing reserved words + properties: + return: + description: this is a reserved python keyword + type: integer + format: int32 + xml: + name: Return + Name: + description: Model for testing model name same as property name + required: + - name + properties: + name: + type: integer + format: int32 + snake_case: + readOnly: true + type: integer + format: int32 + property: + description: this is a reserved python keyword + type: string + xml: + name: Name + 200_response: + 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 + ClassModel: + description: Model for testing model with "_class" property + properties: + _class: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Animal' + - type: object + properties: + breed: + type: string + Cat: + allOf: + - $ref: '#/components/schemas/Animal' + - type: object + properties: + declawed: + type: boolean + Address: + type: object + additionalProperties: + type: integer + Animal: + type: object + discriminator: + propertyName: className + required: + - className + properties: + className: + type: string + color: + type: string + default: red + AnimalFarm: + type: array + items: + $ref: '#/components/schemas/Animal' + FormatTest: + type: object + required: + - number + - byte + - date + - password + properties: + integer: + type: integer + maximum: 100 + minimum: 10 + multipleOf: 2 + int32: + type: integer + format: int32 + int32withValidations: + 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: + 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' + 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 + uuidNoExample: + type: string + format: uuid + 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' + noneProp: + type: 'null' + EnumClass: + type: string + default: '-efg' + enum: + - _abc + - '-efg' + - (xyz) + Enum_Test: + type: object + required: + - enum_string_required + properties: + enum_string: + type: string + enum: + - UPPER + - lower + - '' + enum_string_required: + type: string + enum: + - UPPER + - lower + - '' + enum_integer: + type: integer + format: int32 + enum: + - 1 + - -1 + enum_number: + type: number + format: double + enum: + - 1.1 + - -1.2 + stringEnum: + $ref: '#/components/schemas/StringEnum' + IntegerEnum: + $ref: '#/components/schemas/IntegerEnum' + StringEnumWithDefaultValue: + $ref: '#/components/schemas/StringEnumWithDefaultValue' + IntegerEnumWithDefaultValue: + $ref: '#/components/schemas/IntegerEnumWithDefaultValue' + IntegerEnumOneValue: + $ref: '#/components/schemas/IntegerEnumOneValue' + AdditionalPropertiesClass: + type: object + properties: + map_property: + type: object + additionalProperties: + type: string + map_of_map_property: + type: object + additionalProperties: + type: object + additionalProperties: + type: string + anytype_1: {} + map_with_undeclared_properties_anytype_1: + type: object + map_with_undeclared_properties_anytype_2: + type: object + properties: {} + map_with_undeclared_properties_anytype_3: + type: object + additionalProperties: true + empty_map: + type: object + description: an object with no declared properties and no undeclared + properties, hence it's an empty map. + additionalProperties: false + map_with_undeclared_properties_string: + type: object + additionalProperties: + type: string + MixedPropertiesAndAdditionalPropertiesClass: + type: object + properties: + uuid: + type: string + format: uuid + dateTime: + type: string + format: date-time + map: + type: object + additionalProperties: + $ref: '#/components/schemas/Animal' + Client: + type: object + properties: + client: + type: string + ReadOnlyFirst: + type: object + properties: + bar: + type: string + readOnly: true + baz: + type: string + hasOnlyReadOnly: + type: object + properties: + bar: + type: string + readOnly: true + foo: + type: string + readOnly: true + Capitalization: + type: object + 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 + MapTest: + type: object + properties: + map_map_of_string: + type: object + additionalProperties: + type: object + additionalProperties: + type: string + map_of_enum_string: + type: object + additionalProperties: + type: string + enum: + - UPPER + - lower + direct_map: + type: object + additionalProperties: + type: boolean + indirect_map: + $ref: '#/components/schemas/StringBooleanMap' + ArrayTest: + type: object + properties: + array_of_string: + type: array + items: + type: string + array_array_of_integer: + type: array + items: + type: array + items: + type: integer + format: int64 + array_array_of_model: + type: array + items: + type: array + items: + $ref: '#/components/schemas/ReadOnlyFirst' + NumberOnly: + type: object + properties: + JustNumber: + type: number + ArrayOfNumberOnly: + type: object + properties: + ArrayNumber: + type: array + items: + type: number + ArrayOfArrayOfNumberOnly: + type: object + properties: + ArrayArrayNumber: + type: array + items: + type: array + items: + type: number + EnumArrays: + type: object + properties: + just_symbol: + type: string + enum: + - '>=' + - $ + array_enum: + type: array + items: + type: string + enum: + - fish + - crab + StringEnum: + nullable: true + type: string + enum: + - "placed" + - "approved" + - "delivered" + - 'single quoted' + - |- + multiple + lines + - "double quote \n with newline" + IntegerEnum: + type: integer + enum: + - 0 + - 1 + - 2 + IntegerEnumBig: + type: integer + enum: + - 10 + - 11 + - 12 + StringEnumWithDefaultValue: + type: string + enum: + - placed + - approved + - delivered + default: placed + IntegerEnumWithDefaultValue: + type: integer + enum: + - 0 + - 1 + - 2 + default: 0 + IntegerEnumOneValue: + 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: + $ref: '#/definitions/NumberWithValidations' + myString: + $ref: '#/definitions/String' + myBoolean: + $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: + description: this is a model that allows payloads of type object or number + oneOf: + - $ref: '#/components/schemas/NumberWithValidations' + - $ref: '#/components/schemas/Animal' + - 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: + type: string + Boolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + StringBooleanMap: + additionalProperties: + type: boolean + FileSchemaTestClass: + type: object + properties: + file: + $ref: '#/components/schemas/File' + files: + type: array + items: + $ref: '#/components/schemas/File' + File: + type: object + description: Must be named `File` for test. + properties: + sourceURI: + description: Test capitalization + type: string + ObjectWithDifficultlyNamedProps: + type: object + description: model with properties that have invalid names for python + 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 + HealthCheckResult: + type: object + properties: + NullableMessage: + nullable: true + type: string + description: Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + NullableClass: + type: object + properties: + integer_prop: + type: integer + nullable: true + number_prop: + type: number + nullable: true + boolean_prop: + type: boolean + nullable: true + string_prop: + type: string + nullable: true + date_prop: + type: string + format: date + nullable: true + datetime_prop: + type: string + format: date-time + nullable: true + array_nullable_prop: + type: array + nullable: true + items: + type: object + array_and_items_nullable_prop: + type: array + nullable: true + items: + type: object + nullable: true + array_items_nullable: + type: array + items: + type: object + nullable: true + object_nullable_prop: + type: object + nullable: true + additionalProperties: + type: object + object_and_items_nullable_prop: + type: object + nullable: true + additionalProperties: + type: object + nullable: true + object_items_nullable: + type: object + additionalProperties: + type: object + nullable: true + additionalProperties: + type: object + nullable: true + fruit: + properties: + color: + type: string + oneOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' + apple: + type: object + properties: + cultivar: + type: string + pattern: ^[a-zA-Z\s]*$ + origin: + type: string + pattern: /^[A-Z\s]*$/i + required: + - cultivar + nullable: true + banana: + type: object + properties: + lengthCm: + type: number + required: + - lengthCm + mammal: + oneOf: + - $ref: '#/components/schemas/whale' + - $ref: '#/components/schemas/zebra' + - $ref: '#/components/schemas/Pig' + discriminator: + propertyName: className + whale: + type: object + properties: + hasBaleen: + type: boolean + hasTeeth: + type: boolean + className: + type: string + enum: + - whale + required: + - className + zebra: + type: object + properties: + type: + type: string + enum: + - plains + - mountain + - grevys + className: + type: string + enum: + - zebra + required: + - className + additionalProperties: true + Pig: + oneOf: + - $ref: '#/components/schemas/BasquePig' + - $ref: '#/components/schemas/DanishPig' + discriminator: + propertyName: className + BasquePig: + type: object + properties: + className: + type: string + enum: + - BasquePig + required: + - className + DanishPig: + type: object + properties: + className: + type: string + enum: + - DanishPig + required: + - className + gmFruit: + properties: + color: + type: string + anyOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' + fruitReq: + oneOf: + - type: 'null' + - $ref: '#/components/schemas/appleReq' + - $ref: '#/components/schemas/bananaReq' + appleReq: + type: object + properties: + cultivar: + type: string + mealy: + type: boolean + required: + - cultivar + additionalProperties: false + bananaReq: + type: object + properties: + lengthCm: + type: number + sweet: + type: boolean + required: + - lengthCm + additionalProperties: false + # go-experimental is unable to make Triangle and Quadrilateral models + # correctly https://github.com/OpenAPITools/openapi-generator/issues/6149 + Drawing: + type: object + properties: + mainShape: + # A property whose value is a 'oneOf' type, and the type is referenced instead + # of being defined inline. The value cannot be null. + $ref: '#/components/schemas/Shape' + shapeOrNull: + # A property whose value is a 'oneOf' type, and the type is referenced instead + # of being defined inline. The value may be null because ShapeOrNull has 'null' + # type as a child schema of 'oneOf'. + $ref: '#/components/schemas/ShapeOrNull' + nullableShape: + # A property whose value is a 'oneOf' type, and the type is referenced instead + # of being defined inline. The value may be null because NullableShape has the + # 'nullable: true' attribute. For this specific scenario this is exactly the + # same thing as 'shapeOrNull'. + $ref: '#/components/schemas/NullableShape' + shapes: + type: array + items: + $ref: '#/components/schemas/Shape' + additionalProperties: + # Here the additional properties are specified using a referenced schema. + # This is just to validate the generated code works when using $ref + # under 'additionalProperties'. + $ref: '#/components/schemas/fruit' + Shape: + oneOf: + - $ref: '#/components/schemas/Triangle' + - $ref: '#/components/schemas/Quadrilateral' + discriminator: + propertyName: shapeType + ShapeOrNull: + description: The value may be a shape or the 'null' value. + This is introduced in OAS schema >= 3.1. + oneOf: + - type: 'null' + - $ref: '#/components/schemas/Triangle' + - $ref: '#/components/schemas/Quadrilateral' + discriminator: + 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 nullable composed schema to work, one of its chosen oneOf schemas must be type null + oneOf: + - $ref: '#/components/schemas/Triangle' + - $ref: '#/components/schemas/Quadrilateral' + - type: null + discriminator: + propertyName: shapeType + nullable: true + TriangleInterface: + properties: + shapeType: + type: string + enum: + - 'Triangle' + triangleType: + type: string + required: + - shapeType + - triangleType + Triangle: + oneOf: + - $ref: '#/components/schemas/EquilateralTriangle' + - $ref: '#/components/schemas/IsoscelesTriangle' + - $ref: '#/components/schemas/ScaleneTriangle' + discriminator: + propertyName: triangleType + # Note: the 'additionalProperties' keyword is not specified, which is + # equivalent to allowing undeclared properties of any type. + EquilateralTriangle: + allOf: + - $ref: '#/components/schemas/TriangleInterface' + - type: object + properties: + triangleType: + type: string + enum: + - 'EquilateralTriangle' + IsoscelesTriangle: + allOf: + - $ref: '#/components/schemas/TriangleInterface' + - type: object + properties: + triangleType: + type: string + enum: + - 'IsoscelesTriangle' + ScaleneTriangle: + allOf: + - $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: + - $ref: '#/components/schemas/SimpleQuadrilateral' + - $ref: '#/components/schemas/ComplexQuadrilateral' + discriminator: + propertyName: quadrilateralType + SimpleQuadrilateral: + allOf: + - $ref: '#/components/schemas/QuadrilateralInterface' + - type: object + properties: + quadrilateralType: + type: string + enum: + - 'SimpleQuadrilateral' + ComplexQuadrilateral: + allOf: + - $ref: '#/components/schemas/QuadrilateralInterface' + - type: object + properties: + quadrilateralType: + type: string + enum: + - 'ComplexQuadrilateral' + GrandparentAnimal: + type: object + required: + - pet_type + properties: + pet_type: + type: string + discriminator: + propertyName: pet_type + ParentPet: + type: object + allOf: + - $ref: '#/components/schemas/GrandparentAnimal' + ChildCat: + allOf: + - $ref: '#/components/schemas/ParentPet' + - type: object + properties: + name: + type: string + ArrayOfEnums: + type: array + items: + $ref: '#/components/schemas/StringEnum' + AdditionalPropertiesWithArrayOfEnums: + type: object + additionalProperties: + type: array + items: + $ref: '#/components/schemas/EnumClass' + DateTimeTest: + type: string + default: '2010-01-01T10:10:10.000111+01:00' + example: '2010-01-01T10:10:10.000111+01:00' + format: date-time + ObjectInterface: + type: object + ObjectWithValidations: + type: object + minProperties: 2 + SomeObject: + allOf: + - $ref: '#/components/schemas/ObjectInterface' +# TODO turn this back on later +# AnyType: +# description: this should allow any type because type was not specified + 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: + 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: + type: string + enemyPlayer: + $ref: '#/components/schemas/Player' + 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: + - {} diff --git a/samples/openapi3/client/petstore/python-experimental/.gitignore b/samples/openapi3/client/petstore/python-experimental/.gitignore new file mode 100644 index 000000000000..a62e8aba43f8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/.gitignore @@ -0,0 +1,67 @@ +# 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 new file mode 100644 index 000000000000..611e425676ee --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/.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.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-ignore b/samples/openapi3/client/petstore/python-experimental/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/.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-experimental/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-experimental/.openapi-generator/FILES new file mode 100644 index 000000000000..ad8d63e86a68 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/.openapi-generator/FILES @@ -0,0 +1,262 @@ +.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/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/CatAllOf.md +docs/Category.md +docs/ChildCat.md +docs/ChildCatAllOf.md +docs/ClassModel.md +docs/Client.md +docs/ComplexQuadrilateral.md +docs/ComplexQuadrilateralAllOf.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/DanishPig.md +docs/DateTimeTest.md +docs/DateTimeWithValidations.md +docs/DateWithValidations.md +docs/DefaultApi.md +docs/Dog.md +docs/DogAllOf.md +docs/Drawing.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/EquilateralTriangle.md +docs/EquilateralTriangleAllOf.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/InlineResponseDefault.md +docs/IntegerEnum.md +docs/IntegerEnumBig.md +docs/IntegerEnumOneValue.md +docs/IntegerEnumWithDefaultValue.md +docs/IntegerMax10.md +docs/IntegerMin15.md +docs/IsoscelesTriangle.md +docs/IsoscelesTriangleAllOf.md +docs/Mammal.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/ModelReturn.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/ObjectWithDifficultlyNamedProps.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/ScaleneTriangleAllOf.md +docs/Shape.md +docs/ShapeOrNull.md +docs/SimpleQuadrilateral.md +docs/SimpleQuadrilateralAllOf.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/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_tags_123_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_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/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/complex_quadrilateral_all_of.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/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/dog.py +petstore_api/model/dog_all_of.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/equilateral_triangle_all_of.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/inline_response_default.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/isosceles_triangle_all_of.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/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_difficultly_named_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/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/scalene_triangle_all_of.py +petstore_api/model/shape.py +petstore_api/model/shape_or_null.py +petstore_api/model/simple_quadrilateral.py +petstore_api/model/simple_quadrilateral_all_of.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/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/.openapi-generator/VERSION b/samples/openapi3/client/petstore/python-experimental/.openapi-generator/VERSION new file mode 100644 index 000000000000..0984c4c1ad21 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.4.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python-experimental/.travis.yml b/samples/openapi3/client/petstore/python-experimental/.travis.yml new file mode 100644 index 000000000000..f931f0f74b96 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/.travis.yml @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 000000000000..863c380ebef9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/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 \ 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 new file mode 100644 index 000000000000..5798de014b75 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/README.md @@ -0,0 +1,320 @@ +# 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* | [**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* | [**json_form_data**](docs/FakeApi.md#json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data +*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* | [**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* | [**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) + - [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) + - [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) + - [ComplexQuadrilateralAllOf](docs/ComplexQuadrilateralAllOf.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) + - [DanishPig](docs/DanishPig.md) + - [DateTimeTest](docs/DateTimeTest.md) + - [DateTimeWithValidations](docs/DateTimeWithValidations.md) + - [DateWithValidations](docs/DateWithValidations.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) + - [EquilateralTriangleAllOf](docs/EquilateralTriangleAllOf.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) + - [InlineResponseDefault](docs/InlineResponseDefault.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) + - [IsoscelesTriangleAllOf](docs/IsoscelesTriangleAllOf.md) + - [Mammal](docs/Mammal.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [ModelReturn](docs/ModelReturn.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) + - [ObjectWithDifficultlyNamedProps](docs/ObjectWithDifficultlyNamedProps.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) + - [ScaleneTriangleAllOf](docs/ScaleneTriangleAllOf.md) + - [Shape](docs/Shape.md) + - [ShapeOrNull](docs/ShapeOrNull.md) + - [SimpleQuadrilateral](docs/SimpleQuadrilateral.md) + - [SimpleQuadrilateralAllOf](docs/SimpleQuadrilateralAllOf.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) + - [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/dev-requirements.txt b/samples/openapi3/client/petstore/python-experimental/dev-requirements.txt new file mode 100644 index 000000000000..ccdfca629494 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/dev-requirements.txt @@ -0,0 +1,2 @@ +tox +flake8 diff --git a/samples/openapi3/client/petstore/python-experimental/docs/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-experimental/docs/AdditionalPropertiesClass.md new file mode 100644 index 000000000000..cf88f5b25d9f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/AdditionalPropertiesClass.md @@ -0,0 +1,17 @@ +# 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** | **bool, date, datetime, dict, float, int, list, str** | 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 new file mode 100644 index 000000000000..81d4ee554017 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/AdditionalPropertiesWithArrayOfEnums.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..a6060817c8c4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Address.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..8d43981dc829 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Animal.md @@ -0,0 +1,11 @@ +# 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 new file mode 100644 index 000000000000..04db36a075cf --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/AnimalFarm.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..6ec2e771f866 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/AnotherFakeApi.md @@ -0,0 +1,94 @@ +# 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/ApiResponse.md b/samples/openapi3/client/petstore/python-experimental/docs/ApiResponse.md new file mode 100644 index 000000000000..6206bcbe6116 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ApiResponse.md @@ -0,0 +1,12 @@ +# 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 new file mode 100644 index 000000000000..93f59b3a2e19 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Apple.md @@ -0,0 +1,11 @@ +# 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 new file mode 100644 index 000000000000..1dde25261bcf --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/AppleReq.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..db0bfa793a6b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ArrayHoldingAnyType.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..5b5c89bfd669 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..ce8778c78f69 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ArrayOfEnums.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..2fa514a78659 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..b84215f20ac4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ArrayTest.md @@ -0,0 +1,12 @@ +# 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 new file mode 100644 index 000000000000..d19d241bfeda --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ArrayWithValidationsInItems.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..11b9e97a5c86 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Banana.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..68959cfbd6f8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/BananaReq.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..f6e0141c5fc0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Bar.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..76fa224a3773 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/BasquePig.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..9e64a63c8ee6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Boolean.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..1235414f1e3d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/BooleanEnum.md @@ -0,0 +1,8 @@ +# BooleanEnum + +Type | Description | Notes +------------- | ------------- | ------------- +**bool** | | 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-experimental/docs/Capitalization.md b/samples/openapi3/client/petstore/python-experimental/docs/Capitalization.md new file mode 100644 index 000000000000..a9f4f6ecdae9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Capitalization.md @@ -0,0 +1,15 @@ +# 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 new file mode 100644 index 000000000000..a6d67ac80190 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Cat.md @@ -0,0 +1,9 @@ +# 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/CatAllOf.md b/samples/openapi3/client/petstore/python-experimental/docs/CatAllOf.md new file mode 100644 index 000000000000..f2a9f7d35b7f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/CatAllOf.md @@ -0,0 +1,10 @@ +# CatAllOf + +#### Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **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/Category.md b/samples/openapi3/client/petstore/python-experimental/docs/Category.md new file mode 100644 index 000000000000..a847da44a13f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Category.md @@ -0,0 +1,11 @@ +# 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 new file mode 100644 index 000000000000..08b6b3c1cbde --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ChildCat.md @@ -0,0 +1,9 @@ +# 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/ChildCatAllOf.md b/samples/openapi3/client/petstore/python-experimental/docs/ChildCatAllOf.md new file mode 100644 index 000000000000..1e0f07a36283 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ChildCatAllOf.md @@ -0,0 +1,10 @@ +# ChildCatAllOf + +#### Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**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/ClassModel.md b/samples/openapi3/client/petstore/python-experimental/docs/ClassModel.md new file mode 100644 index 000000000000..97d387878b39 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ClassModel.md @@ -0,0 +1,12 @@ +# 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 new file mode 100644 index 000000000000..7c0ad6e9734b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Client.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..0c647b168957 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ComplexQuadrilateral.md @@ -0,0 +1,9 @@ +# 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/ComplexQuadrilateralAllOf.md b/samples/openapi3/client/petstore/python-experimental/docs/ComplexQuadrilateralAllOf.md new file mode 100644 index 000000000000..d2cb47a3c42d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ComplexQuadrilateralAllOf.md @@ -0,0 +1,10 @@ +# ComplexQuadrilateralAllOf + +#### Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**quadrilateralType** | **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/ComposedAnyOfDifferentTypesNoValidations.md b/samples/openapi3/client/petstore/python-experimental/docs/ComposedAnyOfDifferentTypesNoValidations.md new file mode 100644 index 000000000000..3dad57b962a7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ComposedAnyOfDifferentTypesNoValidations.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..6f0ebdc39e09 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ComposedArray.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..64ba095ebe41 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ComposedBool.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..f295563e7041 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ComposedNone.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..4c52af546f70 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ComposedNumber.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..3939050270d5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ComposedObject.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..59ed1efabc69 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ComposedOneOfDifferentTypes.md @@ -0,0 +1,11 @@ +# 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 new file mode 100644 index 000000000000..37b16f50b4f6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ComposedString.md @@ -0,0 +1,8 @@ +# 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/DanishPig.md b/samples/openapi3/client/petstore/python-experimental/docs/DanishPig.md new file mode 100644 index 000000000000..f239dc97318d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/DanishPig.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..408c95d0f9ae --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/DateTimeTest.md @@ -0,0 +1,8 @@ +# DateTimeTest + +Type | Description | Notes +------------- | ------------- | ------------- +**datetime** | | defaults to isoparse('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 new file mode 100644 index 000000000000..bb2e7e17e71b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/DateTimeWithValidations.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..bce951bc5b5a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/DateWithValidations.md @@ -0,0 +1,8 @@ +# 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/DefaultApi.md b/samples/openapi3/client/petstore/python-experimental/docs/DefaultApi.md new file mode 100644 index 000000000000..768fca5bd474 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/DefaultApi.md @@ -0,0 +1,70 @@ +# 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** +> InlineResponseDefault foo_get() + + + +### Example + +```python +import petstore_api +from petstore_api.api import default_api +from petstore_api.model.inline_response_default import InlineResponseDefault +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 +Type | Description | Notes +------------- | ------------- | ------------- +[**InlineResponseDefault**](InlineResponseDefault.md) | | + + + +[**InlineResponseDefault**](InlineResponseDefault.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/Dog.md b/samples/openapi3/client/petstore/python-experimental/docs/Dog.md new file mode 100644 index 000000000000..851567bc58ad --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Dog.md @@ -0,0 +1,9 @@ +# 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/DogAllOf.md b/samples/openapi3/client/petstore/python-experimental/docs/DogAllOf.md new file mode 100644 index 000000000000..8dfd16400b64 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/DogAllOf.md @@ -0,0 +1,10 @@ +# DogAllOf + +#### Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **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/Drawing.md b/samples/openapi3/client/petstore/python-experimental/docs/Drawing.md new file mode 100644 index 000000000000..e535601a731c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Drawing.md @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 000000000000..78ecdb677e41 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/EnumArrays.md @@ -0,0 +1,11 @@ +# 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 new file mode 100644 index 000000000000..1399e59181db --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/EnumClass.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..e720f3bf92d3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/EnumTest.md @@ -0,0 +1,18 @@ +# 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 new file mode 100644 index 000000000000..834bcb30fd6c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/EquilateralTriangle.md @@ -0,0 +1,9 @@ +# 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/EquilateralTriangleAllOf.md b/samples/openapi3/client/petstore/python-experimental/docs/EquilateralTriangleAllOf.md new file mode 100644 index 000000000000..8e151789e012 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/EquilateralTriangleAllOf.md @@ -0,0 +1,10 @@ +# EquilateralTriangleAllOf + +#### Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**triangleType** | **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/FakeApi.md b/samples/openapi3/client/petstore/python-experimental/docs/FakeApi.md new file mode 100644 index 000000000000..45fdc4a5c1c3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/FakeApi.md @@ -0,0 +1,2604 @@ +# 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 | +[**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 +[**json_form_data**](FakeApi.md#json_form_data) | **GET** /fake/jsonFormData | test json serialization of form data +[**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 | +[**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 | +[**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( + source_uri="source_uri_example", + ), + ], + ) + 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_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() + 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) + +# **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="AUR,rZ#UM/?R,Fp^l6$ARjbhJk C", + byte='YQ==', + binary=open('/path/to/file', 'rb'), + date=isoparse('1970-01-01').date(), + date_time=isoparse('2020-02-02T20:20:20.22222Z'), + 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 isoparse('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) + +# **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) + +# **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_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) + +# **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 new file mode 100644 index 000000000000..6d5c732f70e0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/FakeClassnameTags123Api.md @@ -0,0 +1,105 @@ +# 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_tags_123_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_tags_123_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 new file mode 100644 index 000000000000..d541f9f0ab4e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/File.md @@ -0,0 +1,12 @@ +# 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 new file mode 100644 index 000000000000..e7bdc36bfd51 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/FileSchemaTestClass.md @@ -0,0 +1,11 @@ +# 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 new file mode 100644 index 000000000000..e948b10caef8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Foo.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..472216aa457b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/FormatTest.md @@ -0,0 +1,30 @@ +# 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 new file mode 100644 index 000000000000..42684ab7a152 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Fruit.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..eceb328ee611 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/FruitReq.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..13879f263219 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/GmFruit.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..ed51b572862a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/GrandparentAnimal.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..14ac98c0769a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# 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 new file mode 100644 index 000000000000..8ce835f39a4e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/HealthCheckResult.md @@ -0,0 +1,12 @@ +# 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/InlineResponseDefault.md b/samples/openapi3/client/petstore/python-experimental/docs/InlineResponseDefault.md new file mode 100644 index 000000000000..d28a65a74d9f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/InlineResponseDefault.md @@ -0,0 +1,10 @@ +# InlineResponseDefault + +#### 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] + +[[Back to Model list]](../README.md#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 new file mode 100644 index 000000000000..32d665414464 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnum.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..58d94b3102b0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnumBig.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..6fea6c1d4419 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnumOneValue.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..b95a839f9bfc --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/IntegerEnumWithDefaultValue.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..768902e0aca2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/IntegerMax10.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..35043be2fadb --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/IntegerMin15.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..7891fd5aa745 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/IsoscelesTriangle.md @@ -0,0 +1,9 @@ +# 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/IsoscelesTriangleAllOf.md b/samples/openapi3/client/petstore/python-experimental/docs/IsoscelesTriangleAllOf.md new file mode 100644 index 000000000000..12881c0177ab --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/IsoscelesTriangleAllOf.md @@ -0,0 +1,10 @@ +# IsoscelesTriangleAllOf + +#### Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**triangleType** | **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/Mammal.md b/samples/openapi3/client/petstore/python-experimental/docs/Mammal.md new file mode 100644 index 000000000000..6ecc91576e74 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Mammal.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..b842ca9985c5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/MapTest.md @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 000000000000..f8406a0af426 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# 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 new file mode 100644 index 000000000000..71af8e104479 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Model200Response.md @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 000000000000..35abb51e239c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ModelReturn.md @@ -0,0 +1,12 @@ +# 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/Name.md b/samples/openapi3/client/petstore/python-experimental/docs/Name.md new file mode 100644 index 000000000000..446d314fbd15 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Name.md @@ -0,0 +1,14 @@ +# 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 new file mode 100644 index 000000000000..e5bf9b9be8c9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/NoAdditionalProperties.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..5f2a1280eb2c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/NullableClass.md @@ -0,0 +1,21 @@ +# 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 new file mode 100644 index 000000000000..1419c735f3c2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/NullableShape.md @@ -0,0 +1,11 @@ +# 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. For a nullable composed schema to work, one of its chosen oneOf schemas must be type null + +#### 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 new file mode 100644 index 000000000000..c01cb8067835 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/NullableString.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..63e3c42fdbd1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Number.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..699674314e09 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/NumberOnly.md @@ -0,0 +1,10 @@ +# 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 new file mode 100644 index 000000000000..9fe4c99f8d8e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/NumberWithValidations.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..1ce1b34d41d8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ObjectInterface.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..637175bc2f4e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ObjectModelWithRefProps.md @@ -0,0 +1,14 @@ +# 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/ObjectWithDifficultlyNamedProps.md b/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithDifficultlyNamedProps.md new file mode 100644 index 000000000000..cb45c6b10efc --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithDifficultlyNamedProps.md @@ -0,0 +1,14 @@ +# 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/ObjectWithValidations.md b/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithValidations.md new file mode 100644 index 000000000000..3950d2ab95ec --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ObjectWithValidations.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..374172ad32ca --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Order.md @@ -0,0 +1,15 @@ +# 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 new file mode 100644 index 000000000000..28a57b84feaa --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ParentPet.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..8eec44141d5d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Pet.md @@ -0,0 +1,17 @@ +# 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 new file mode 100644 index 000000000000..9bcb83080704 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/PetApi.md @@ -0,0 +1,1362 @@ +# 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 | +**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 new file mode 100644 index 000000000000..97259b026f98 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Pig.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..2daf47240c75 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Player.md @@ -0,0 +1,13 @@ +# 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 new file mode 100644 index 000000000000..e840c9b8fd0d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Quadrilateral.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..ee7c4db4ba4c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/QuadrilateralInterface.md @@ -0,0 +1,11 @@ +# 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 new file mode 100644 index 000000000000..a6c2e4524b7f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# 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 new file mode 100644 index 000000000000..941e9e63117f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ScaleneTriangle.md @@ -0,0 +1,9 @@ +# 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/ScaleneTriangleAllOf.md b/samples/openapi3/client/petstore/python-experimental/docs/ScaleneTriangleAllOf.md new file mode 100644 index 000000000000..3ac4ed161258 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ScaleneTriangleAllOf.md @@ -0,0 +1,10 @@ +# ScaleneTriangleAllOf + +#### Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**triangleType** | **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/Shape.md b/samples/openapi3/client/petstore/python-experimental/docs/Shape.md new file mode 100644 index 000000000000..798438fbd2ba --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Shape.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..17fa7c50577c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/ShapeOrNull.md @@ -0,0 +1,11 @@ +# 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 new file mode 100644 index 000000000000..d9ce2f02b010 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/SimpleQuadrilateral.md @@ -0,0 +1,9 @@ +# 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/SimpleQuadrilateralAllOf.md b/samples/openapi3/client/petstore/python-experimental/docs/SimpleQuadrilateralAllOf.md new file mode 100644 index 000000000000..e8bf2861915a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/SimpleQuadrilateralAllOf.md @@ -0,0 +1,10 @@ +# SimpleQuadrilateralAllOf + +#### Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**quadrilateralType** | **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/SomeObject.md b/samples/openapi3/client/petstore/python-experimental/docs/SomeObject.md new file mode 100644 index 000000000000..55a308e4f863 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/SomeObject.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..8c02dca9ab3a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/SpecialModelName.md @@ -0,0 +1,12 @@ +# 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 new file mode 100644 index 000000000000..80f9a368f5fd --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/StoreApi.md @@ -0,0 +1,391 @@ +# 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=isoparse('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 new file mode 100644 index 000000000000..ca058fd710b8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/String.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..89b85004e978 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/StringBooleanMap.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..bf610d102850 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/StringEnum.md @@ -0,0 +1,10 @@ +# StringEnum + +Type | Description | Notes +------------- | ------------- | ------------- +typing.Union[str, None, ] | | must be one of ["placed", "approved", "delivered", "single quoted", '''multiple +lines''', '''double quote + 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 new file mode 100644 index 000000000000..08a337a52642 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/StringEnumWithDefaultValue.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..870752b1df8e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/StringWithValidation.md @@ -0,0 +1,8 @@ +# 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 new file mode 100644 index 000000000000..42cf6ecbc853 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Tag.md @@ -0,0 +1,11 @@ +# 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 new file mode 100644 index 000000000000..0820ec390f06 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Triangle.md @@ -0,0 +1,9 @@ +# 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 new file mode 100644 index 000000000000..11c7c8e45413 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/TriangleInterface.md @@ -0,0 +1,11 @@ +# 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/User.md b/samples/openapi3/client/petstore/python-experimental/docs/User.md new file mode 100644 index 000000000000..cfff38a62691 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/User.md @@ -0,0 +1,21 @@ +# 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] +**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 new file mode 100644 index 000000000000..0e77fad4125c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/UserApi.md @@ -0,0 +1,784 @@ +# 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_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_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_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_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 new file mode 100644 index 000000000000..f0b2dbc51ef8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Whale.md @@ -0,0 +1,12 @@ +# 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 new file mode 100644 index 000000000000..ae12668a3a17 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Zebra.md @@ -0,0 +1,11 @@ +# 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 new file mode 100644 index 000000000000..ced3be2b0c7b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/git_push.sh @@ -0,0 +1,58 @@ +#!/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 new file mode 100644 index 000000000000..26b0467759de --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/__init__.py @@ -0,0 +1,31 @@ +# 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/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/__init__.py new file mode 100644 index 000000000000..840e9f0cd908 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/__init__.py @@ -0,0 +1,3 @@ +# 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-experimental/petstore_api/api/another_fake_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.py new file mode 100644 index 000000000000..a6e0483cf682 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api.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 +""" + +from petstore_api.api_client import ApiClient +from petstore_api.api.another_fake_api_endpoints.call_123_test_special_tags import Call123TestSpecialTags + + +class AnotherFakeApi( + Call123TestSpecialTags, + 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/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 new file mode 100644 index 000000000000..b97333110467 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/another_fake_api_endpoints/call_123_test_special_tags.py @@ -0,0 +1,161 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..28b822701b69 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api.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 +""" + +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/foo_get.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api_endpoints/foo_get.py new file mode 100644 index 000000000000..b704f12197a0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/default_api_endpoints/foo_get.py @@ -0,0 +1,138 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + +from petstore_api.model.inline_response_default import InlineResponseDefault + +_path = '/foo' +_method = 'GET' +SchemaFor0ResponseBodyApplicationJson = InlineResponseDefault + + +@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 + """ + + _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=_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 new file mode 100644 index 000000000000..7a81465ef0f9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api.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 +""" + +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.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.json_form_data import JsonFormData +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_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.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, + EndpointParameters, + EnumParameters, + FakeHealthGet, + GroupParameters, + InlineAdditionalProperties, + JsonFormData, + Mammal, + NumberWithValidations, + ObjectModelWithRefProps, + ParameterCollisions, + QueryParameterCollectionFormat, + 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/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 new file mode 100644 index 000000000000..f0d07f512051 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/additional_properties_with_array_of_enums.py @@ -0,0 +1,158 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..9c44cbce5077 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/array_model.py @@ -0,0 +1,157 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..83af2ce00ca8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/array_of_enums.py @@ -0,0 +1,158 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..c46e584ab427 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/body_with_file_schema.py @@ -0,0 +1,146 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..a99f338d61b7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/body_with_query_params.py @@ -0,0 +1,186 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _query_params = [] + for parameter in ( + request_query_query, + ): + parameter_data = query_params.get(parameter.name, unset) + if parameter_data is unset: + continue + serialized_data = parameter.serialize(parameter_data) + _query_params.extend(serialized_data) + + _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=_path, + method=_method, + query_params=tuple(_query_params), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + 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 new file mode 100644 index 000000000000..49566ef541d6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/boolean.py @@ -0,0 +1,155 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..ac4d37279ebf --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/case_sensitive_params.py @@ -0,0 +1,174 @@ +# 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 + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _query_params = [] + 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 + serialized_data = parameter.serialize(parameter_data) + _query_params.extend(serialized_data) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=_path, + method=_method, + query_params=tuple(_query_params), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + 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 new file mode 100644 index 000000000000..d1812acdfb65 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/client_model.py @@ -0,0 +1,161 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..7f3ecf420450 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/composed_one_of_different_types.py @@ -0,0 +1,157 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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/endpoint_parameters.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/endpoint_parameters.py new file mode 100644 index 000000000000..63faaf2db9a6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/endpoint_parameters.py @@ -0,0 +1,288 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + +# body param + + +class SchemaForRequestBodyApplicationXWwwFormUrlencoded( + DictSchema +): + _required_property_names = set(( + )) + + + 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, ], + 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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + integer=integer, + int32=int32, + int64=int64, + string=string, + binary=binary, + date=date, + dateTime=dateTime, + password=password, + callback=callback, + _instantiation_metadata=_instantiation_metadata, + **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 + """ + + _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=_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 new file mode 100644 index 000000000000..7d8e080429d0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/enum_parameters.py @@ -0,0 +1,480 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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._enum_by_value[">"](">") + + @classmethod + @property + def DOLLAR(cls): + return cls._enum_by_value["$"]("$") + + +class EnumQueryStringSchema( + _SchemaEnumMaker( + enum_value_to_name={ + "_abc": "_ABC", + "-efg": "EFG", + "(xyz)": "XYZ", + } + ), + StrSchema +): + + @classmethod + @property + def _ABC(cls): + return cls._enum_by_value["_abc"]("_abc") + + @classmethod + @property + def EFG(cls): + return cls._enum_by_value["-efg"]("-efg") + + @classmethod + @property + def XYZ(cls): + return cls._enum_by_value["(xyz)"]("(xyz)") + + +class EnumQueryIntegerSchema( + _SchemaEnumMaker( + enum_value_to_name={ + 1: "POSITIVE_1", + -2: "NEGATIVE_2", + } + ), + Int32Schema +): + + @classmethod + @property + def POSITIVE_1(cls): + return cls._enum_by_value[1](1) + + @classmethod + @property + def NEGATIVE_2(cls): + return cls._enum_by_value[-2](-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._enum_by_value[1.1](1.1) + + @classmethod + @property + def NEGATIVE_1_PT_2(cls): + return cls._enum_by_value[-1.2](-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._enum_by_value[">"](">") + + @classmethod + @property + def DOLLAR(cls): + return cls._enum_by_value["$"]("$") + + +class EnumHeaderStringSchema( + _SchemaEnumMaker( + enum_value_to_name={ + "_abc": "_ABC", + "-efg": "EFG", + "(xyz)": "XYZ", + } + ), + StrSchema +): + + @classmethod + @property + def _ABC(cls): + return cls._enum_by_value["_abc"]("_abc") + + @classmethod + @property + def EFG(cls): + return cls._enum_by_value["-efg"]("-efg") + + @classmethod + @property + def XYZ(cls): + return cls._enum_by_value["(xyz)"]("(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._enum_by_value[">"](">") + + @classmethod + @property + def DOLLAR(cls): + return cls._enum_by_value["$"]("$") + + + class enum_form_string( + _SchemaEnumMaker( + enum_value_to_name={ + "_abc": "_ABC", + "-efg": "EFG", + "(xyz)": "XYZ", + } + ), + StrSchema + ): + + @classmethod + @property + def _ABC(cls): + return cls._enum_by_value["_abc"]("_abc") + + @classmethod + @property + def EFG(cls): + return cls._enum_by_value["-efg"]("-efg") + + @classmethod + @property + def XYZ(cls): + return cls._enum_by_value["(xyz)"]("(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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + enum_form_string_array=enum_form_string_array, + enum_form_string=enum_form_string, + _instantiation_metadata=_instantiation_metadata, + **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) + + _query_params = [] + 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 + serialized_data = parameter.serialize(parameter_data) + _query_params.extend(serialized_data) + + _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=_path, + method=_method, + query_params=tuple(_query_params), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + 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 new file mode 100644 index 000000000000..831241cba68d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/fake_health_get.py @@ -0,0 +1,135 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..dc590cb91372 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/group_parameters.py @@ -0,0 +1,234 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _query_params = [] + 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 + serialized_data = parameter.serialize(parameter_data) + _query_params.extend(serialized_data) + + _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=_path, + method=_method, + query_params=tuple(_query_params), + 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 new file mode 100644 index 000000000000..0acc3f4491e1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/inline_additional_properties.py @@ -0,0 +1,164 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + +# body param + + +class SchemaForRequestBodyApplicationJson( + DictSchema +): + _additional_properties = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 + """ + + _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=_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 new file mode 100644 index 000000000000..591f9417e3b5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/json_form_data.py @@ -0,0 +1,164 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + +# body param + + +class SchemaForRequestBodyApplicationXWwwFormUrlencoded( + DictSchema +): + _required_property_names = set(( + )) + param = StrSchema + param2 = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 + """ + + _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=_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 new file mode 100644 index 000000000000..4b402d4e9614 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/mammal.py @@ -0,0 +1,160 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..ac82ec1bca53 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/number_with_validations.py @@ -0,0 +1,157 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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_model_with_ref_props.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/object_model_with_ref_props.py new file mode 100644 index 000000000000..aaa919ec758e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/object_model_with_ref_props.py @@ -0,0 +1,157 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..c355d0e1183c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/parameter_collisions.py @@ -0,0 +1,425 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _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) + + _query_params = [] + 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 + serialized_data = parameter.serialize(parameter_data) + _query_params.extend(serialized_data) + + _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=_path, + method=_method, + path_params=_path_params, + query_params=tuple(_query_params), + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + 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 new file mode 100644 index 000000000000..14076fea22ba --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/query_parameter_collection_format.py @@ -0,0 +1,228 @@ +# 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 + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _query_params = [] + 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 + serialized_data = parameter.serialize(parameter_data) + _query_params.extend(serialized_data) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=_path, + method=_method, + query_params=tuple(_query_params), + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + 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 new file mode 100644 index 000000000000..000d30c64ef1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/string.py @@ -0,0 +1,155 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..51c9bd862e86 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/string_enum.py @@ -0,0 +1,157 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..87fa4f8dbcc7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/upload_download_file.py @@ -0,0 +1,159 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..8fbdf9bbdb89 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/upload_file.py @@ -0,0 +1,182 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + +from petstore_api.model.api_response import ApiResponse + +# body param + + +class SchemaForRequestBodyMultipartFormData( + DictSchema +): + _required_property_names = set(( + )) + additionalMetadata = StrSchema + file = BinarySchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + additionalMetadata: typing.Union[additionalMetadata, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + additionalMetadata=additionalMetadata, + _instantiation_metadata=_instantiation_metadata, + **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 + """ + + _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=_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 new file mode 100644 index 000000000000..19c7745793ae --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_api_endpoints/upload_files.py @@ -0,0 +1,184 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + files=files, + _instantiation_metadata=_instantiation_metadata, + **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 + """ + + _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=_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_tags_123_api.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.py new file mode 100644 index 000000000000..cda926e1d0a7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api.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 +""" + +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/fake_classname_tags_123_api_endpoints/classname.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api_endpoints/classname.py new file mode 100644 index 000000000000..d8157f7f4cfd --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/fake_classname_tags_123_api_endpoints/classname.py @@ -0,0 +1,165 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py new file mode 100644 index 000000000000..83efafb3ec37 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use 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/add_pet.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/add_pet.py new file mode 100644 index 000000000000..7f04e4cc3c8d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/add_pet.py @@ -0,0 +1,182 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..de6d86ed2128 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/delete_pet.py @@ -0,0 +1,196 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _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) + + _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=_path, + method=_method, + path_params=_path_params, + 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 new file mode 100644 index 000000000000..d6b31e361f56 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/find_pets_by_status.py @@ -0,0 +1,246 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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._enum_by_value["available"]("available") + + @classmethod + @property + def PENDING(cls): + return cls._enum_by_value["pending"]("pending") + + @classmethod + @property + def SOLD(cls): + return cls._enum_by_value["sold"]("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) + + _query_params = [] + for parameter in ( + request_query_status, + ): + parameter_data = query_params.get(parameter.name, unset) + if parameter_data is unset: + continue + serialized_data = parameter.serialize(parameter_data) + _query_params.extend(serialized_data) + + _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=_path, + method=_method, + query_params=tuple(_query_params), + 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 new file mode 100644 index 000000000000..a4c39c6ae347 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/find_pets_by_tags.py @@ -0,0 +1,220 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _query_params = [] + for parameter in ( + request_query_tags, + ): + parameter_data = query_params.get(parameter.name, unset) + if parameter_data is unset: + continue + serialized_data = parameter.serialize(parameter_data) + _query_params.extend(serialized_data) + + _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=_path, + method=_method, + query_params=tuple(_query_params), + 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 new file mode 100644 index 000000000000..533b2ae23cfa --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/get_pet_by_id.py @@ -0,0 +1,209 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _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) + + _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=_path, + method=_method, + path_params=_path_params, + 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 new file mode 100644 index 000000000000..71bdf386bc91 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/update_pet.py @@ -0,0 +1,194 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..6535b584ac8e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/update_pet_with_form.py @@ -0,0 +1,208 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + name=name, + status=status, + _instantiation_metadata=_instantiation_metadata, + **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) + + _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) + + _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=_path, + method=_method, + path_params=_path_params, + 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.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/upload_file.py new file mode 100644 index 000000000000..faa353d8d30e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/upload_file.py @@ -0,0 +1,216 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + FileSchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + FileBase, + Schema, + _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 = FileSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + additionalMetadata: typing.Union[additionalMetadata, Unset] = unset, + file: typing.Union[file, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + additionalMetadata=additionalMetadata, + file=file, + _instantiation_metadata=_instantiation_metadata, + **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 UploadFile(api_client.Api): + + def upload_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, + ) -> typing.Union[ + ApiResponseFor200, + api_client.ApiResponseWithoutDeserialization + ]: + """ + uploads an image + Parameters use leading underscores to prevent collisions with user defined + parameters from the source openapi spec + """ + self._verify_typed_dict_inputs(RequestPathParams, path_params) + + _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) + + _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=_path, + method=_method, + path_params=_path_params, + headers=_headers, + fields=_fields, + body=_body, + auth_settings=_auth, + ) + + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + 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 new file mode 100644 index 000000000000..214bf7a41b2e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/upload_file_with_required_file.py @@ -0,0 +1,225 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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(( + )) + additionalMetadata = StrSchema + requiredFile = BinarySchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + additionalMetadata: typing.Union[additionalMetadata, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + additionalMetadata=additionalMetadata, + _instantiation_metadata=_instantiation_metadata, + **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) + + _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) + + _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=_path, + method=_method, + path_params=_path_params, + 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 new file mode 100644 index 000000000000..d4f494e25be9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/pet_api_endpoints/upload_image.py @@ -0,0 +1,223 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + additionalMetadata=additionalMetadata, + _instantiation_metadata=_instantiation_metadata, + **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) + + _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) + + _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=_path, + method=_method, + path_params=_path_params, + 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 new file mode 100644 index 000000000000..3685a1728049 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api.py @@ -0,0 +1,31 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use 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/delete_order.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/delete_order.py new file mode 100644 index 000000000000..9dbbf03607f9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/delete_order.py @@ -0,0 +1,166 @@ +# 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 + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _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) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=_path, + method=_method, + path_params=_path_params, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + 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 new file mode 100644 index 000000000000..e5e5aca7eb05 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/get_inventory.py @@ -0,0 +1,156 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 + """ + + _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=_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 new file mode 100644 index 000000000000..11f819f27b32 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/get_order_by_id.py @@ -0,0 +1,214 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _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) + + _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=_path, + method=_method, + path_params=_path_params, + 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 new file mode 100644 index 000000000000..ef9f9c3ba631 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/store_api_endpoints/place_order.py @@ -0,0 +1,179 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..1975100b9e69 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_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.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/create_user.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_user.py new file mode 100644 index 000000000000..8627997a2fb5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_user.py @@ -0,0 +1,151 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..8694e9582ffd --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_users_with_array_input.py @@ -0,0 +1,160 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..d1c0a1e0e875 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/create_users_with_list_input.py @@ -0,0 +1,160 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + + _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=_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 new file mode 100644 index 000000000000..1d3b65308201 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/delete_user.py @@ -0,0 +1,166 @@ +# 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 + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _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) + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=_path, + method=_method, + path_params=_path_params, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + 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 new file mode 100644 index 000000000000..2a2af60d64bd --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/get_user_by_name.py @@ -0,0 +1,205 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _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) + + _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=_path, + method=_method, + path_params=_path_params, + 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 new file mode 100644 index 000000000000..c63a4e482d14 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/login_user.py @@ -0,0 +1,224 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _query_params = [] + for parameter in ( + request_query_username, + request_query_password, + ): + parameter_data = query_params.get(parameter.name, unset) + if parameter_data is unset: + continue + serialized_data = parameter.serialize(parameter_data) + _query_params.extend(serialized_data) + + _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=_path, + method=_method, + query_params=tuple(_query_params), + 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 new file mode 100644 index 000000000000..1e6f9443fcec --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/logout_user.py @@ -0,0 +1,119 @@ +# 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 + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + """ + # TODO add cookie handling + + response = self.api_client.call_api( + resource_path=_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 new file mode 100644 index 000000000000..fcd3f6dcde43 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api/user_api_endpoints/update_user.py @@ -0,0 +1,198 @@ +# 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 +from urllib3._collections import HTTPHeaderDict + +from petstore_api import api_client, exceptions +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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) + + _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) + + _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=_path, + method=_method, + path_params=_path_params, + headers=_headers, + fields=_fields, + body=_body, + stream=stream, + timeout=timeout, + ) + + if skip_deserialization: + api_response = api_client.ApiResponseWithoutDeserialization(response=response) + else: + response_for_status = _status_code_to_response.get(str(response.status)) + if response_for_status: + api_response = response_for_status.deserialize(response, self.api_client.configuration) + 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 new file mode 100644 index 000000000000..38220b88f5dc --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/api_client.py @@ -0,0 +1,1379 @@ +# coding: utf-8 +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use 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 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 ( + Decimal, + NoneClass, + BoolClass, + Schema, + FileIO, + BinarySchema, + InstantiationMetadata, + 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, int, float)): + # instances based on primitive classes + return 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 ParameterSerializerBase: + @staticmethod + def __serialize_number( + in_data: typing.Union[int, float], name: str, prefix='' + ) -> typing.Tuple[typing.Tuple[str, str]]: + return tuple([(name, prefix + str(in_data))]) + + @staticmethod + def __serialize_str( + in_data: str, name: str, prefix='' + ) -> typing.Tuple[typing.Tuple[str, str]]: + return tuple([(name, prefix + quote(in_data))]) + + @staticmethod + def __serialize_bool(in_data: bool, name: str, prefix='') -> typing.Tuple[typing.Tuple[str, str]]: + if in_data: + return tuple([(name, prefix + 'true')]) + return tuple([(name, prefix + 'false')]) + + @staticmethod + def __urlencode(in_data: typing.Any) -> str: + return quote(str(in_data)) + + def __serialize_list( + self, + in_data: typing.List[typing.Any], + style: ParameterStyle, + name: str, + explode: bool, + empty_val: typing.Union[typing.Tuple[str, str], typing.Tuple] = tuple(), + prefix: str = '', + separator: str = ',', + ) -> typing.Tuple[typing.Union[typing.Tuple[str, str], typing.Tuple], ...]: + if not in_data: + return empty_val + if explode and style in { + ParameterStyle.FORM, + ParameterStyle.MATRIX, + ParameterStyle.SPACE_DELIMITED, + ParameterStyle.PIPE_DELIMITED + }: + if style is ParameterStyle.FORM: + return tuple((name, prefix + self.__urlencode(val)) for val in in_data) + else: + joined_vals = prefix + separator.join(name + '=' + self.__urlencode(val) for val in in_data) + else: + joined_vals = prefix + separator.join(map(self.__urlencode, in_data)) + return tuple([(name, joined_vals)]) + + def __form_item_representation(self, in_data: typing.Any) -> typing.Optional[str]: + if isinstance(in_data, none_type): + return None + elif isinstance(in_data, list): + if not in_data: + return None + raise ApiValueError('Unable to generate a form representation of {}'.format(in_data)) + elif isinstance(in_data, dict): + if not in_data: + return None + raise ApiValueError('Unable to generate a form representation of {}'.format(in_data)) + elif isinstance(in_data, (bool, bytes)): + raise ApiValueError('Unable to generate a form representation of {}'.format(in_data)) + # str, float, int + return self.__urlencode(in_data) + + def __serialize_dict( + self, + in_data: typing.Dict[str, typing.Any], + style: ParameterStyle, + name: str, + explode: bool, + empty_val: typing.Union[typing.Tuple[str, str], typing.Tuple] = tuple(), + prefix: str = '', + separator: str = ',', + ) -> typing.Tuple[typing.Tuple[str, str]]: + if not in_data: + return empty_val + if all(val is None for val in in_data.values()): + return empty_val + + form_items = {} + if style is ParameterStyle.FORM: + for key, val in in_data.items(): + new_val = self.__form_item_representation(val) + if new_val is None: + continue + form_items[key] = new_val + + if explode: + if style is ParameterStyle.FORM: + return tuple((key, prefix + val) for key, val in form_items.items()) + elif style in { + ParameterStyle.SIMPLE, + ParameterStyle.LABEL, + ParameterStyle.MATRIX, + ParameterStyle.SPACE_DELIMITED, + ParameterStyle.PIPE_DELIMITED + }: + joined_vals = prefix + separator.join(key + '=' + self.__urlencode(val) for key, val in in_data.items()) + else: + raise ApiValueError(f'Invalid style {style} for dict serialization with explode=True') + elif style is ParameterStyle.FORM: + joined_vals = prefix + separator.join(key + separator + val for key, val in form_items.items()) + else: + joined_vals = prefix + separator.join( + key + separator + self.__urlencode(val) for key, val in in_data.items()) + return tuple([(name, joined_vals)]) + + def _serialize_x( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + style: ParameterStyle, + name: str, + explode: bool, + empty_val: typing.Union[typing.Tuple[str, str], typing.Tuple] = (), + prefix: str = '', + separator: str = ',', + ) -> typing.Tuple[typing.Tuple[str, str], ...]: + if isinstance(in_data, none_type): + return empty_val + elif isinstance(in_data, bool): + # must be before int check + return self.__serialize_bool(in_data, name=name, prefix=prefix) + elif isinstance(in_data, (int, float)): + return self.__serialize_number(in_data, name=name, prefix=prefix) + elif isinstance(in_data, str): + return self.__serialize_str(in_data, name=name, prefix=prefix) + elif isinstance(in_data, list): + return self.__serialize_list( + in_data, + style=style, + name=name, + explode=explode, + empty_val=empty_val, + prefix=prefix, + separator=separator + ) + elif isinstance(in_data, dict): + return self.__serialize_dict( + in_data, + style=style, + name=name, + explode=explode, + empty_val=empty_val, + prefix=prefix, + separator=separator + ) + + +class StyleFormSerializer(ParameterSerializerBase): + + def _serialize_form( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + name: str, + explode: bool, + ) -> typing.Tuple[typing.Tuple[str, str], ...]: + return self._serialize_x(in_data, style=ParameterStyle.FORM, name=name, explode=explode) + + +class StyleSimpleSerializer(ParameterSerializerBase): + + def _serialize_simple_tuple( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + name: str, + explode: bool, + in_type: ParameterInType, + ) -> typing.Tuple[typing.Tuple[str, str], ...]: + if in_type is ParameterInType.HEADER: + empty_val = () + else: + empty_val = ((name, ''),) + return self._serialize_x(in_data, style=ParameterStyle.SIMPLE, name=name, explode=explode, empty_val=empty_val) + + +@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] + ) -> typing.Tuple[typing.Tuple[str, str]]: + return tuple([(self.name, 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]: + empty_val = ((self.name, ''),) + prefix = '.' + separator = '.' + return self._remove_empty_and_cast( + self._serialize_x( + in_data, + style=ParameterStyle.LABEL, + name=self.name, + explode=self.explode, + empty_val=empty_val, + prefix=prefix, + separator=separator + ) + ) + + def __serialize_matrix( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list] + ) -> typing.Dict[str, str]: + separator = ',' + if in_data == '': + prefix = ';' + self.name + elif isinstance(in_data, (dict, list)) and self.explode: + prefix = ';' + separator = ';' + else: + prefix = ';' + self.name + '=' + empty_val = ((self.name, ''),) + return self._remove_empty_and_cast( + self._serialize_x( + in_data, + style=ParameterStyle.MATRIX, + name=self.name, + explode=self.explode, + prefix=prefix, + empty_val=empty_val, + separator=separator + ) + ) + + def _serialize_simple( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list], + ) -> typing.Dict[str, str]: + tuple_data = self._serialize_simple_tuple(in_data, self.name, self.explode, self.in_type) + return self._remove_empty_and_cast(tuple_data) + + 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: + tuple_data = self._serialize_json(cast_in_data) + return self._remove_empty_and_cast(tuple_data) + 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: 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.QUERY, + required=required, + style=style, + explode=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] + ) -> typing.Tuple[typing.Tuple[str, str], ...]: + separator = '%20' + empty_val = () + return self._serialize_x( + in_data, + style=ParameterStyle.SPACE_DELIMITED, + name=self.name, + explode=self.explode, + separator=separator, + empty_val=empty_val + ) + + def __serialize_pipe_delimited( + self, + in_data: typing.Union[None, int, float, str, bool, dict, list] + ) -> typing.Tuple[typing.Tuple[str, str], ...]: + separator = '|' + empty_val = () + return self._serialize_x( + in_data, + style=ParameterStyle.PIPE_DELIMITED, + name=self.name, + explode=self.explode, + separator=separator, + empty_val=empty_val + ) + + def serialize( + self, + in_data: typing.Union[ + Schema, Decimal, int, float, str, date, datetime, None, bool, list, tuple, dict, frozendict] + ) -> typing.Tuple[typing.Tuple[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, explode=self.explode, name=self.name) + elif self.style is ParameterStyle.SPACE_DELIMITED: + return self.__serialize_space_delimited(cast_in_data) + elif self.style is ParameterStyle.PIPE_DELIMITED: + return self.__serialize_pipe_delimited(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: + return self._serialize_json(cast_in_data) + 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: 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.COOKIE, + required=required, + style=style, + explode=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.Tuple[typing.Tuple[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: + return self._serialize_form(cast_in_data, explode=self.explode, name=self.name) + # 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: + return self._serialize_json(cast_in_data) + 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], + ) -> HTTPHeaderDict[str, str]: + tuple_data = self._serialize_simple_tuple(in_data, self.name, self.explode, self.in_type) + return self.__to_headers(tuple_data) + + 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: + return self._serialize_simple(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: + tuple_data = self._serialize_json(cast_in_data) + return self.__to_headers(tuple_data) + 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 + + +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. + """ + + def __init__( + self, + schema: typing.Type[Schema], + encoding: typing.Optional[typing.Dict[str, Encoding]] = None, + ): + self.schema = schema + self.encoding = encoding + + +@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 OpenApiResponse: + 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: + decoded_data = response.data.decode("utf-8") + return json.loads(decoded_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 + + def deserialize(self, response: urllib3.HTTPResponse, configuration: Configuration) -> ApiResponse: + content_type = response.getheader('content-type') + deserialized_body = unset + streamed = response.supports_chunked_reads() + if self.content is not None: + if content_type == 'application/json': + body_data = self.__deserialize_json(response) + elif content_type == 'application/octet-stream': + body_data = self.__deserialize_application_octet_stream(response) + else: + raise NotImplementedError('Deserialization of {} has not yet been implemented'.format(content_type)) + body_schema = self.content[content_type].schema + _instantiation_metadata = InstantiationMetadata(from_server=True, configuration=configuration) + deserialized_body = body_schema._from_openapi_data( + body_data, _instantiation_metadata=_instantiation_metadata) + elif streamed: + response.release_conn() + + deserialized_headers = unset + if self.headers is not None: + deserialized_headers = unset + + 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, + path_params: typing.Optional[typing.Dict[str, typing.Any]] = None, + query_params: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = 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, + 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 + + # path parameters + if path_params: + for k, v in path_params.items(): + # specified safe chars, encode everything + resource_path = resource_path.replace( + '{%s}' % k, + quote(str(v), safe=self.configuration.safe_chars_for_path_param) + ) + + # auth setting + self.update_params_for_auth(headers, query_params, + 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, + query_params=query_params, + headers=headers, + fields=fields, + body=body, + stream=stream, + timeout=timeout, + ) + 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.Tuple[typing.Tuple[str, str], ...]] = 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, + 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 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, + path_params, + query_params, + headers, + body, + fields, + auth_settings, + stream, + timeout, + host, + ) + + return self.pool.apply_async( + self.__call_api, + ( + resource_path, + method, + path_params, + query_params, + headers, + body, + json, + fields, + auth_settings, + stream, + timeout, + host, + ) + ) + + def request( + self, + method: str, + url: str, + query_params: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, + 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, + stream=stream, + timeout=timeout, + headers=headers) + elif method == "HEAD": + return self.rest_client.HEAD(url, + query_params=query_params, + stream=stream, + timeout=timeout, + headers=headers) + elif method == "OPTIONS": + return self.rest_client.OPTIONS(url, + query_params=query_params, + headers=headers, + fields=fields, + stream=stream, + timeout=timeout, + body=body) + elif method == "POST": + return self.rest_client.POST(url, + query_params=query_params, + headers=headers, + fields=fields, + stream=stream, + timeout=timeout, + body=body) + elif method == "PUT": + return self.rest_client.PUT(url, + query_params=query_params, + headers=headers, + fields=fields, + stream=stream, + timeout=timeout, + body=body) + elif method == "PATCH": + return self.rest_client.PATCH(url, + query_params=query_params, + headers=headers, + fields=fields, + stream=stream, + timeout=timeout, + body=body) + elif method == "DELETE": + return self.rest_client.DELETE(url, + query_params=query_params, + 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, querys, auth_settings, + resource_path, method, body): + """Updates header and query params based on authentication setting. + + :param headers: Header parameters dict to be updated. + :param querys: 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(). + """ + 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 + 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': + querys.append((auth_setting['key'], auth_setting['value'])) + 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): + """ + 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 + ) -> typing.Dict[str, tuple[tuple[str, str], ...]]: + 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) + fields = self._serialize_form(cast_in_data, explode=True, name='') + if not fields: + return {} + return {'fields': fields} + + 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 content_type == 'application/json': + 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 new file mode 100644 index 000000000000..5a98862bba09 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/apis/__init__.py @@ -0,0 +1,24 @@ +# 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 .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_tags_123_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 new file mode 100644 index 000000000000..f7c2a3ff91eb --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/configuration.py @@ -0,0 +1,610 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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/exceptions.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/exceptions.py new file mode 100644 index 000000000000..ed422fd2d0e2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/exceptions.py @@ -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 +""" + + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None): + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + 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 + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None): + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None): + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +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() + else: + self.status = status + self.reason = reason + self.body = None + self.headers = None + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.body: + error_message += "HTTP response body: {0}\n".format(self.body) + + return error_message + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/__init__.py new file mode 100644 index 000000000000..027452f37a87 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/__init__.py @@ -0,0 +1,5 @@ +# we can not import model classes here because that would create a circular +# reference which would not work in python2 +# do not import all models into this module because that uses a lot of memory and stack frames +# if you need the ability to import all models from one package, import them with +# from petstore_api.models import ModelA, ModelB 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 new file mode 100644 index 000000000000..a5e4f0a45d9b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/additional_properties_class.py @@ -0,0 +1,211 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + map_property (dict,): + map_of_map_property (dict,): + anytype_1 (): + map_with_undeclared_properties_anytype_1 (dict,): + map_with_undeclared_properties_anytype_2 (dict,): + map_with_undeclared_properties_anytype_3 (dict,): + empty_map (dict,): an object with no declared properties and no undeclared properties, hence it's an empty map. + map_with_undeclared_properties_string (dict,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class map_property( + DictSchema + ): + _additional_properties = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + + + class map_of_map_property( + DictSchema + ): + + + class _additional_properties( + DictSchema + ): + _additional_properties = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) + + + class map_with_undeclared_properties_string( + DictSchema + ): + _additional_properties = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + 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, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..db4d01003d30 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/additional_properties_with_array_of_enums.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class _additional_properties( + ListSchema + ): + + @classmethod + @property + def _items(cls) -> typing.Type['EnumClass']: + return EnumClass + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..d088fe451588 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/address.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _additional_properties = IntSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..783f9026bd5a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/animal.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + className (str,): + color (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + _discriminator(cls) -> dict: the key is the required discriminator propertyName + the value is a dict mapping from a string name to the corresponding Schema class + """ + _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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + className=className, + color=color, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..1868ee5ee69d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/animal_farm.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _items (Schema): the schema definition of the array items + """ + + @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/api_response.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/api_response.py new file mode 100644 index 000000000000..505d16f177a1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/api_response.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + code (int,): + type (str,): + message (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + 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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + code=code, + type=type, + message=message, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..07991225ef50 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/apple.py @@ -0,0 +1,120 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class Apple( + _SchemaTypeChecker(typing.Union[frozendict, none_type, ]), + DictBase, + NoneBase, + Schema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + cultivar (str,): + origin (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + origin=origin, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..c94a177b0ac9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/apple_req.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + cultivar (str,): + mealy (bool,): + """ + _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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + cultivar=cultivar, + mealy=mealy, + _instantiation_metadata=_instantiation_metadata, + ) 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 new file mode 100644 index 000000000000..90f05d5eb124 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_holding_any_type.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _items (Schema): the schema definition of the array items + """ + _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 new file mode 100644 index 000000000000..6f9cd63088ba --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_of_array_of_number_only.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + ArrayArrayNumber (tuple,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class ArrayArrayNumber( + ListSchema + ): + + + class _items( + ListSchema + ): + _items = NumberSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + ArrayArrayNumber: typing.Union[ArrayArrayNumber, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + ArrayArrayNumber=ArrayArrayNumber, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..ddb90807d27d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_of_enums.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _items (Schema): the schema definition of the array items + """ + + @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 new file mode 100644 index 000000000000..1ee632533c37 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_of_number_only.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + ArrayNumber (tuple,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class ArrayNumber( + ListSchema + ): + _items = NumberSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + ArrayNumber: typing.Union[ArrayNumber, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + ArrayNumber=ArrayNumber, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..f69faad445ef --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_test.py @@ -0,0 +1,129 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + array_of_string (tuple,): + array_array_of_integer (tuple,): + array_array_of_model (tuple,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + 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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + 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, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..b34bcf6c27f5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/array_with_validations_in_items.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _items (Schema): the schema definition of the array items + _validations (dict): the validations which apply to the current Schema + 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. + """ + + + 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 new file mode 100644 index 000000000000..9cdf3cd55c6b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/banana.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + lengthCm (int, float,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _required_property_names = set(( + 'lengthCm', + )) + lengthCm = NumberSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + lengthCm: lengthCm, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + lengthCm=lengthCm, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..1cf74f05e3e6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/banana_req.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + lengthCm (int, float,): + sweet (bool,): + """ + _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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + lengthCm=lengthCm, + sweet=sweet, + _instantiation_metadata=_instantiation_metadata, + ) 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 new file mode 100644 index 000000000000..afbf24b8a222 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/bar.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 new file mode 100644 index 000000000000..c11f9ab4bf93 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/basque_pig.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + className (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _required_property_names = set(( + 'className', + )) + + + class className( + _SchemaEnumMaker( + enum_value_to_name={ + "BasquePig": "BASQUEPIG", + } + ), + StrSchema + ): + + @classmethod + @property + def BASQUEPIG(cls): + return cls._enum_by_value["BasquePig"]("BasquePig") + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + className: className, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + className=className, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..e9f974616fcb --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/boolean.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 new file mode 100644 index 000000000000..50b7181cc7e5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/boolean_enum.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class BooleanEnum( + _SchemaEnumMaker( + enum_value_to_name={ + True: "TRUE", + } + ), + BoolSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + """ + + @classmethod + @property + def TRUE(cls): + return cls._enum_by_value[True](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 new file mode 100644 index 000000000000..8b508242ff2f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/capitalization.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + smallCamel (str,): + CapitalCamel (str,): + small_Snake (str,): + Capital_Snake (str,): + SCA_ETH_Flow_Points (str,): + ATT_NAME (str,): Name of the pet + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + 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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + 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, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..080d2bde5b8c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/cat.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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': [ + Animal, + CatAllOf, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + +from petstore_api.model.animal import Animal +from petstore_api.model.cat_all_of import CatAllOf diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/cat_all_of.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/cat_all_of.py new file mode 100644 index 000000000000..b08ff9b66f0b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/cat_all_of.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class CatAllOf( + DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + declawed (bool,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + declawed = BoolSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + declawed: typing.Union[declawed, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + declawed=declawed, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) 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 new file mode 100644 index 000000000000..abc7c3fc95ac --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/category.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + id (int,): + name (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + name=name, + id=id, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..e33b977dea1a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/child_cat.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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': [ + ParentPet, + ChildCatAllOf, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + +from petstore_api.model.child_cat_all_of import ChildCatAllOf +from petstore_api.model.parent_pet import ParentPet diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/child_cat_all_of.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/child_cat_all_of.py new file mode 100644 index 000000000000..aadedf154812 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/child_cat_all_of.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class ChildCatAllOf( + DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + name (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + name = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + name: typing.Union[name, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + name=name, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) 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 new file mode 100644 index 000000000000..54118dfb5d64 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/class_model.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + + Attributes: + _class (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _class = StrSchema + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _class: typing.Union[_class, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _class=_class, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..713b3156872c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/client.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + client (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + client = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + client: typing.Union[client, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + client=client, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..8a7f81af7539 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/complex_quadrilateral.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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': [ + QuadrilateralInterface, + ComplexQuadrilateralAllOf, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + +from petstore_api.model.complex_quadrilateral_all_of import ComplexQuadrilateralAllOf +from petstore_api.model.quadrilateral_interface import QuadrilateralInterface diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/complex_quadrilateral_all_of.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/complex_quadrilateral_all_of.py new file mode 100644 index 000000000000..095c96095ac0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/complex_quadrilateral_all_of.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class ComplexQuadrilateralAllOf( + DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + quadrilateralType (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class quadrilateralType( + _SchemaEnumMaker( + enum_value_to_name={ + "ComplexQuadrilateral": "COMPLEXQUADRILATERAL", + } + ), + StrSchema + ): + + @classmethod + @property + def COMPLEXQUADRILATERAL(cls): + return cls._enum_by_value["ComplexQuadrilateral"]("ComplexQuadrilateral") + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + quadrilateralType: typing.Union[quadrilateralType, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + quadrilateralType=quadrilateralType, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) 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 new file mode 100644 index 000000000000..fb200660c6e2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_any_of_different_types_no_validations.py @@ -0,0 +1,141 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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 + 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, + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..6a9d0e19c3f9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_array.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _items (Schema): the schema definition of the array items + """ + _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 new file mode 100644 index 000000000000..b74990ba87a5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_bool.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + """ + + @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 + allOf_0 = AnyTypeSchema + return { + 'allOf': [ + allOf_0, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[bool, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) 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 new file mode 100644 index 000000000000..ac6f516344f4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_none.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + """ + + @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 + allOf_0 = AnyTypeSchema + return { + 'allOf': [ + allOf_0, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) 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 new file mode 100644 index 000000000000..e932e138bcc3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_number.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + """ + + @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 + allOf_0 = AnyTypeSchema + return { + 'allOf': [ + allOf_0, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[float, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) 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 new file mode 100644 index 000000000000..92942e256c40 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_object.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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 + allOf_0 = AnyTypeSchema + return { + 'allOf': [ + allOf_0, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..0a454dbceede --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_one_of_different_types.py @@ -0,0 +1,162 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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 + 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, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..dec60c328efe --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/composed_string.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + """ + + @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 + allOf_0 = AnyTypeSchema + return { + 'allOf': [ + allOf_0, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[str, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) 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 new file mode 100644 index 000000000000..d269be73d17d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/danish_pig.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + className (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _required_property_names = set(( + 'className', + )) + + + class className( + _SchemaEnumMaker( + enum_value_to_name={ + "DanishPig": "DANISHPIG", + } + ), + StrSchema + ): + + @classmethod + @property + def DANISHPIG(cls): + return cls._enum_by_value["DanishPig"]("DanishPig") + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + className: className, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + className=className, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..837edc52f030 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/date_time_test.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 new file mode 100644 index 000000000000..d7bc79a11f95 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/date_time_with_validations.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _validations (dict): the validations which apply to the current Schema + 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. + """ + 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 new file mode 100644 index 000000000000..a61d8da1b01f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/date_with_validations.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _validations (dict): the validations which apply to the current Schema + 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. + """ + pass 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 new file mode 100644 index 000000000000..dbfc2b137707 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/dog.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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': [ + Animal, + DogAllOf, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + +from petstore_api.model.animal import Animal +from petstore_api.model.dog_all_of import DogAllOf diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/dog_all_of.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/dog_all_of.py new file mode 100644 index 000000000000..1767fc983aef --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/dog_all_of.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class DogAllOf( + DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + breed (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + breed = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + breed: typing.Union[breed, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + breed=breed, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) 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 new file mode 100644 index 000000000000..5196bd01cce1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/drawing.py @@ -0,0 +1,133 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + mainShape (): + shapeOrNull (): + nullableShape (): + shapes (tuple,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + mainShape=mainShape, + shapeOrNull=shapeOrNull, + nullableShape=nullableShape, + shapes=shapes, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..54d293edd166 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/enum_arrays.py @@ -0,0 +1,139 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + just_symbol (str,): + array_enum (tuple,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class just_symbol( + _SchemaEnumMaker( + enum_value_to_name={ + ">=": "GREATER_THAN_EQUALS", + "$": "DOLLAR", + } + ), + StrSchema + ): + + @classmethod + @property + def GREATER_THAN_EQUALS(cls): + return cls._enum_by_value[">="](">=") + + @classmethod + @property + def DOLLAR(cls): + return cls._enum_by_value["$"]("$") + + + class array_enum( + ListSchema + ): + + + class _items( + _SchemaEnumMaker( + enum_value_to_name={ + "fish": "FISH", + "crab": "CRAB", + } + ), + StrSchema + ): + + @classmethod + @property + def FISH(cls): + return cls._enum_by_value["fish"]("fish") + + @classmethod + @property + def CRAB(cls): + return cls._enum_by_value["crab"]("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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + just_symbol=just_symbol, + array_enum=array_enum, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..475c1dd6ca26 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/enum_class.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 re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + """ + + @classmethod + @property + def _ABC(cls): + return cls._enum_by_value["_abc"]("_abc") + + @classmethod + @property + def EFG(cls): + return cls._enum_by_value["-efg"]("-efg") + + @classmethod + @property + def XYZ(cls): + return cls._enum_by_value["(xyz)"]("(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 new file mode 100644 index 000000000000..77769e3cd748 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/enum_test.py @@ -0,0 +1,243 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + enum_string (str,): + enum_string_required (str,): + enum_integer (int,): + enum_number (float,): + stringEnum (): + IntegerEnum (): + StringEnumWithDefaultValue (): + IntegerEnumWithDefaultValue (): + IntegerEnumOneValue (): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _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._enum_by_value["UPPER"]("UPPER") + + @classmethod + @property + def LOWER(cls): + return cls._enum_by_value["lower"]("lower") + + @classmethod + @property + def EMPTY(cls): + return cls._enum_by_value[""]("") + + + class enum_string_required( + _SchemaEnumMaker( + enum_value_to_name={ + "UPPER": "UPPER", + "lower": "LOWER", + "": "EMPTY", + } + ), + StrSchema + ): + + @classmethod + @property + def UPPER(cls): + return cls._enum_by_value["UPPER"]("UPPER") + + @classmethod + @property + def LOWER(cls): + return cls._enum_by_value["lower"]("lower") + + @classmethod + @property + def EMPTY(cls): + return cls._enum_by_value[""]("") + + + class enum_integer( + _SchemaEnumMaker( + enum_value_to_name={ + 1: "POSITIVE_1", + -1: "NEGATIVE_1", + } + ), + Int32Schema + ): + + @classmethod + @property + def POSITIVE_1(cls): + return cls._enum_by_value[1](1) + + @classmethod + @property + def NEGATIVE_1(cls): + return cls._enum_by_value[-1](-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._enum_by_value[1.1](1.1) + + @classmethod + @property + def NEGATIVE_1_PT_2(cls): + return cls._enum_by_value[-1.2](-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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + 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, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..69bf6944cf7a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/equilateral_triangle.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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': [ + TriangleInterface, + EquilateralTriangleAllOf, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + +from petstore_api.model.equilateral_triangle_all_of import EquilateralTriangleAllOf +from petstore_api.model.triangle_interface import TriangleInterface diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/equilateral_triangle_all_of.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/equilateral_triangle_all_of.py new file mode 100644 index 000000000000..fb6edf7c7490 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/equilateral_triangle_all_of.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class EquilateralTriangleAllOf( + DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + triangleType (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class triangleType( + _SchemaEnumMaker( + enum_value_to_name={ + "EquilateralTriangle": "EQUILATERALTRIANGLE", + } + ), + StrSchema + ): + + @classmethod + @property + def EQUILATERALTRIANGLE(cls): + return cls._enum_by_value["EquilateralTriangle"]("EquilateralTriangle") + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + triangleType: typing.Union[triangleType, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + triangleType=triangleType, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) 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 new file mode 100644 index 000000000000..30ccd52a5f56 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/file.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 re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + sourceURI (str,): Test capitalization + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + sourceURI = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + sourceURI: typing.Union[sourceURI, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + sourceURI=sourceURI, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..f0f6f4d9d83a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/file_schema_test_class.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + file (): + files (tuple,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + file=file, + files=files, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..2160642188d6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/foo.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + bar (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + bar = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + bar: typing.Union[bar, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + bar=bar, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..913a2a90d1b3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/format_test.py @@ -0,0 +1,276 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + integer (int,): + int32 (int,): + int32withValidations (int,): + int64 (int,): + number (int, float,): + float (float,): this is a reserved python keyword + float32 (float,): + double (float,): + float64 (float,): + arrayWithUniqueItems (tuple,): + string (str,): + byte (str,): + binary (): + date (date,): + dateTime (datetime,): + uuid (str,): + uuidNoExample (str,): + password (str,): + pattern_with_digits (str,): A string that is a 10 digit number. Can have leading zeros. + pattern_with_digits_and_delimiter (str,): A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + noneProp ( none_type,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _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 = StrSchema + uuidNoExample = StrSchema + + + 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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + 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, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..77d38d632d42 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/fruit.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + color (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + color = StrSchema + + @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': [ + Apple, + Banana, + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + color: typing.Union[color, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + color=color, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..37fcf71a44b4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/fruit_req.py @@ -0,0 +1,111 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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 + oneOf_0 = NoneSchema + return { + 'allOf': [ + ], + 'oneOf': [ + oneOf_0, + AppleReq, + BananaReq, + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..ab342907147c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/gm_fruit.py @@ -0,0 +1,113 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + color (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + color = StrSchema + + @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': [ + ], + 'anyOf': [ + Apple, + Banana, + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + color: typing.Union[color, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + color=color, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..f5625407bc7b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/grandparent_animal.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 re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + pet_type (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + _discriminator(cls) -> dict: the key is the required discriminator propertyName + the value is a dict mapping from a string name to the corresponding Schema class + """ + _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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + pet_type=pet_type, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..3a84082bd471 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/has_only_read_only.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + bar (str,): + foo (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + bar = StrSchema + foo = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + bar: typing.Union[bar, Unset] = unset, + foo: typing.Union[foo, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + bar=bar, + foo=foo, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..9cf48be2b363 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/health_check_result.py @@ -0,0 +1,110 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + NullableMessage (str, none_type,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class NullableMessage( + _SchemaTypeChecker(typing.Union[none_type, str, ]), + StrBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[str, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + NullableMessage: typing.Union[NullableMessage, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + NullableMessage=NullableMessage, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/inline_response_default.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/inline_response_default.py new file mode 100644 index 000000000000..6b0f32db72ac --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/inline_response_default.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 re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class InlineResponseDefault( + DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + string (): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @classmethod + @property + def string(cls) -> typing.Type['Foo']: + return Foo + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + string: typing.Union['Foo', Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + string=string, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + +from petstore_api.model.foo import Foo 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 new file mode 100644 index 000000000000..02a228957b69 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum.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 re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + """ + + @classmethod + @property + def POSITIVE_0(cls): + return cls._enum_by_value[0](0) + + @classmethod + @property + def POSITIVE_1(cls): + return cls._enum_by_value[1](1) + + @classmethod + @property + def POSITIVE_2(cls): + return cls._enum_by_value[2](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 new file mode 100644 index 000000000000..babc39df7d43 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum_big.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 re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + """ + + @classmethod + @property + def POSITIVE_10(cls): + return cls._enum_by_value[10](10) + + @classmethod + @property + def POSITIVE_11(cls): + return cls._enum_by_value[11](11) + + @classmethod + @property + def POSITIVE_12(cls): + return cls._enum_by_value[12](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 new file mode 100644 index 000000000000..fa7e4258cbbb --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum_one_value.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + """ + + @classmethod + @property + def POSITIVE_0(cls): + return cls._enum_by_value[0](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 new file mode 100644 index 000000000000..cb5860a0bdbe --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_enum_with_default_value.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 re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + """ + + @classmethod + @property + def POSITIVE_0(cls): + return cls._enum_by_value[0](0) + + @classmethod + @property + def POSITIVE_1(cls): + return cls._enum_by_value[1](1) + + @classmethod + @property + def POSITIVE_2(cls): + return cls._enum_by_value[2](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 new file mode 100644 index 000000000000..affe4283ac61 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_max10.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _validations (dict): the validations which apply to the current Schema + 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. + """ + 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 new file mode 100644 index 000000000000..6a6488136d16 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/integer_min15.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _validations (dict): the validations which apply to the current Schema + 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. + """ + 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 new file mode 100644 index 000000000000..b8527d08df55 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/isosceles_triangle.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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': [ + TriangleInterface, + IsoscelesTriangleAllOf, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + +from petstore_api.model.isosceles_triangle_all_of import IsoscelesTriangleAllOf +from petstore_api.model.triangle_interface import TriangleInterface diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/isosceles_triangle_all_of.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/isosceles_triangle_all_of.py new file mode 100644 index 000000000000..8d9bc65556f3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/isosceles_triangle_all_of.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class IsoscelesTriangleAllOf( + DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + triangleType (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class triangleType( + _SchemaEnumMaker( + enum_value_to_name={ + "IsoscelesTriangle": "ISOSCELESTRIANGLE", + } + ), + StrSchema + ): + + @classmethod + @property + def ISOSCELESTRIANGLE(cls): + return cls._enum_by_value["IsoscelesTriangle"]("IsoscelesTriangle") + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + triangleType: typing.Union[triangleType, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + triangleType=triangleType, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) 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 new file mode 100644 index 000000000000..fd1784636b2b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/mammal.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + _discriminator(cls) -> dict: the key is the required discriminator propertyName + the value is a dict mapping from a string name to the corresponding Schema class + """ + + @classmethod + @property + def _discriminator(cls): + return { + 'className': { + 'Pig': Pig, + 'whale': Whale, + 'zebra': Zebra, + } + } + + @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': [ + Whale, + Zebra, + Pig, + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..90e2f053e683 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/map_test.py @@ -0,0 +1,204 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + map_map_of_string (dict,): + map_of_enum_string (dict,): + direct_map (dict,): + indirect_map (): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class map_map_of_string( + DictSchema + ): + + + class _additional_properties( + DictSchema + ): + _additional_properties = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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._enum_by_value["UPPER"]("UPPER") + + @classmethod + @property + def LOWER(cls): + return cls._enum_by_value["lower"]("lower") + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + + + class direct_map( + DictSchema + ): + _additional_properties = BoolSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + 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, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..e3a39533757c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/mixed_properties_and_additional_properties_class.py @@ -0,0 +1,121 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + uuid (str,): + dateTime (datetime,): + map (dict,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + uuid = StrSchema + dateTime = DateTimeSchema + + + class map( + DictSchema + ): + + @classmethod + @property + def _additional_properties(cls) -> typing.Type['Animal']: + return Animal + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + uuid=uuid, + dateTime=dateTime, + map=map, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) 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 new file mode 100644 index 000000000000..c47980d5a7f4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/model200_response.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + + Attributes: + name (int,): + class (str,): this is a reserved python keyword + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + name = Int32Schema + _class = StrSchema + locals()['class'] = _class + del locals()['_class'] + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + name: typing.Union[name, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + name=name, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..81116280224e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/model_return.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + + Attributes: + return (int,): this is a reserved python keyword + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _return = Int32Schema + locals()['return'] = _return + del locals()['_return'] + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) 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 new file mode 100644 index 000000000000..7343223c4d21 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/name.py @@ -0,0 +1,102 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + + Attributes: + name (int,): + snake_case (int,): + property (str,): this is a reserved python keyword + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _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, None, list, tuple, bytes], + name: name, + snake_case: typing.Union[snake_case, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + name=name, + snake_case=snake_case, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..910b8bc1f117 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/no_additional_properties.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + id (int,): + petId (int,): + """ + _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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + id=id, + petId=petId, + _instantiation_metadata=_instantiation_metadata, + ) 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 new file mode 100644 index 000000000000..45743da43945 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/nullable_class.py @@ -0,0 +1,425 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + integer_prop (int, none_type,): + number_prop (int, float, none_type,): + boolean_prop (bool, none_type,): + string_prop (str, none_type,): + date_prop (date, none_type,): + datetime_prop (datetime, none_type,): + array_nullable_prop (tuple, none_type,): + array_and_items_nullable_prop (tuple, none_type,): + array_items_nullable (tuple,): + object_nullable_prop (dict, none_type,): + object_and_items_nullable_prop (dict, none_type,): + object_items_nullable (dict,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class integer_prop( + _SchemaTypeChecker(typing.Union[none_type, Decimal, ]), + IntBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[int, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) + + + class number_prop( + _SchemaTypeChecker(typing.Union[none_type, Decimal, ]), + NumberBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[float, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) + + + class boolean_prop( + _SchemaTypeChecker(typing.Union[none_type, bool, ]), + BoolBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[bool, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) + + + class string_prop( + _SchemaTypeChecker(typing.Union[none_type, str, ]), + StrBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[str, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) + + + class date_prop( + _SchemaTypeChecker(typing.Union[none_type, str, ]), + DateBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) + + + class datetime_prop( + _SchemaTypeChecker(typing.Union[none_type, str, ]), + DateTimeBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) + + + class array_nullable_prop( + _SchemaTypeChecker(typing.Union[tuple, none_type, ]), + ListBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[list, tuple, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) + + + class array_and_items_nullable_prop( + _SchemaTypeChecker(typing.Union[tuple, none_type, ]), + ListBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[list, tuple, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) + + + class array_items_nullable( + ListSchema + ): + + + class _items( + _SchemaTypeChecker(typing.Union[frozendict, none_type, ]), + DictBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[dict, frozendict, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + + + class object_nullable_prop( + _SchemaTypeChecker(typing.Union[frozendict, none_type, ]), + DictBase, + NoneBase, + Schema + ): + _additional_properties = DictSchema + + def __new__( + cls, + *args: typing.Union[dict, frozendict, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + + + class object_and_items_nullable_prop( + _SchemaTypeChecker(typing.Union[frozendict, none_type, ]), + DictBase, + NoneBase, + Schema + ): + + + class _additional_properties( + _SchemaTypeChecker(typing.Union[frozendict, none_type, ]), + DictBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[dict, frozendict, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + + def __new__( + cls, + *args: typing.Union[dict, frozendict, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + + + class object_items_nullable( + DictSchema + ): + + + class _additional_properties( + _SchemaTypeChecker(typing.Union[frozendict, none_type, ]), + DictBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[dict, frozendict, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + + + class _additional_properties( + _SchemaTypeChecker(typing.Union[frozendict, none_type, ]), + DictBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[dict, frozendict, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + 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, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..7c4e30792344 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/nullable_shape.py @@ -0,0 +1,125 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. The 'nullable' attribute was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema >= 3.1. For a nullable composed schema to work, one of its chosen oneOf schemas must be type null + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + _discriminator(cls) -> dict: the key is the required discriminator propertyName + the value is a dict mapping from a string name to the corresponding Schema class + """ + + @classmethod + @property + def _discriminator(cls): + return { + 'shapeType': { + 'Quadrilateral': Quadrilateral, + 'Triangle': Triangle, + } + } + + @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 + oneOf_2 = NoneSchema + return { + 'allOf': [ + ], + 'oneOf': [ + Triangle, + Quadrilateral, + oneOf_2, + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..2386522587dc --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/nullable_string.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class NullableString( + _SchemaTypeChecker(typing.Union[none_type, str, ]), + StrBase, + NoneBase, + Schema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + """ + + def __new__( + cls, + *args: typing.Union[str, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) 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 new file mode 100644 index 000000000000..c4c4695e8be8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/number.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 new file mode 100644 index 000000000000..ff476caf0321 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/number_only.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + JustNumber (int, float,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + JustNumber = NumberSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + JustNumber: typing.Union[JustNumber, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + JustNumber=JustNumber, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..25ec9cdf00fc --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/number_with_validations.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _validations (dict): the validations which apply to the current Schema + 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. + """ + 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 new file mode 100644 index 000000000000..a5e32358a317 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_interface.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 new file mode 100644 index 000000000000..99ca8288ee81 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_model_with_ref_props.py @@ -0,0 +1,106 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + + Attributes: + myNumber (): + myString (str,): + myBoolean (bool,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + myNumber=myNumber, + myString=myString, + myBoolean=myBoolean, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + +from petstore_api.model.number_with_validations import NumberWithValidations 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 new file mode 100644 index 000000000000..11c22fd99f75 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_difficultly_named_props.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + + Attributes: + $special[property.name] (int,): + 123-list (str,): + 123Number (int,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _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, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..c55d028c3744 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/object_with_validations.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _validations (dict): the validations which apply to the current Schema + 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 (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..b00c227a86c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/order.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + id (int,): + petId (int,): + quantity (int,): + shipDate (datetime,): + status (str,): Order Status + complete (bool,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + 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._enum_by_value["placed"]("placed") + + @classmethod + @property + def APPROVED(cls): + return cls._enum_by_value["approved"]("approved") + + @classmethod + @property + def DELIVERED(cls): + return cls._enum_by_value["delivered"]("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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + id=id, + petId=petId, + quantity=quantity, + shipDate=shipDate, + status=status, + complete=complete, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..b9066defb501 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/parent_pet.py @@ -0,0 +1,120 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + _discriminator(cls) -> dict: the key is the required discriminator propertyName + the value is a dict mapping from a string name to the corresponding Schema class + """ + + @classmethod + @property + def _discriminator(cls): + return { + 'pet_type': { + 'ChildCat': ChildCat, + } + } + + @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': [ + GrandparentAnimal, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..f602e6e722d6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/pet.py @@ -0,0 +1,163 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + + Attributes: + id (int,): + category (): + name (str,): + photoUrls (tuple,): + tags (tuple,): + status (str,): pet status in the store + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _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._enum_by_value["available"]("available") + + @classmethod + @property + def PENDING(cls): + return cls._enum_by_value["pending"]("pending") + + @classmethod + @property + def SOLD(cls): + return cls._enum_by_value["sold"]("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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + name=name, + photoUrls=photoUrls, + id=id, + category=category, + tags=tags, + status=status, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..02ef6df613b5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/pig.py @@ -0,0 +1,121 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + _discriminator(cls) -> dict: the key is the required discriminator propertyName + the value is a dict mapping from a string name to the corresponding Schema class + """ + + @classmethod + @property + def _discriminator(cls): + return { + 'className': { + 'BasquePig': BasquePig, + 'DanishPig': DanishPig, + } + } + + @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': [ + BasquePig, + DanishPig, + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..b568eadf36e7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/player.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + + Attributes: + name (str,): + enemyPlayer (): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _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, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + name=name, + enemyPlayer=enemyPlayer, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..e5e8dd8788af --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/quadrilateral.py @@ -0,0 +1,121 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + _discriminator(cls) -> dict: the key is the required discriminator propertyName + the value is a dict mapping from a string name to the corresponding Schema class + """ + + @classmethod + @property + def _discriminator(cls): + return { + 'quadrilateralType': { + 'ComplexQuadrilateral': ComplexQuadrilateral, + 'SimpleQuadrilateral': SimpleQuadrilateral, + } + } + + @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': [ + SimpleQuadrilateral, + ComplexQuadrilateral, + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..606805b40eee --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/quadrilateral_interface.py @@ -0,0 +1,111 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + shapeType (str,): + quadrilateralType (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _required_property_names = set(( + 'shapeType', + 'quadrilateralType', + )) + + + class shapeType( + _SchemaEnumMaker( + enum_value_to_name={ + "Quadrilateral": "QUADRILATERAL", + } + ), + StrSchema + ): + + @classmethod + @property + def QUADRILATERAL(cls): + return cls._enum_by_value["Quadrilateral"]("Quadrilateral") + quadrilateralType = StrSchema + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + shapeType: shapeType, + quadrilateralType: quadrilateralType, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + shapeType=shapeType, + quadrilateralType=quadrilateralType, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..136a772cd00d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/read_only_first.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + bar (str,): + baz (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + bar = StrSchema + baz = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + bar: typing.Union[bar, Unset] = unset, + baz: typing.Union[baz, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + bar=bar, + baz=baz, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..0639b5aeb3c1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/scalene_triangle.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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': [ + TriangleInterface, + ScaleneTriangleAllOf, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + +from petstore_api.model.scalene_triangle_all_of import ScaleneTriangleAllOf +from petstore_api.model.triangle_interface import TriangleInterface diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/scalene_triangle_all_of.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/scalene_triangle_all_of.py new file mode 100644 index 000000000000..9e031ca5a74d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/scalene_triangle_all_of.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class ScaleneTriangleAllOf( + DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + triangleType (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class triangleType( + _SchemaEnumMaker( + enum_value_to_name={ + "ScaleneTriangle": "SCALENETRIANGLE", + } + ), + StrSchema + ): + + @classmethod + @property + def SCALENETRIANGLE(cls): + return cls._enum_by_value["ScaleneTriangle"]("ScaleneTriangle") + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + triangleType: typing.Union[triangleType, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + triangleType=triangleType, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) 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 new file mode 100644 index 000000000000..6142062fbc7e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/shape.py @@ -0,0 +1,121 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + _discriminator(cls) -> dict: the key is the required discriminator propertyName + the value is a dict mapping from a string name to the corresponding Schema class + """ + + @classmethod + @property + def _discriminator(cls): + return { + 'shapeType': { + 'Quadrilateral': Quadrilateral, + 'Triangle': Triangle, + } + } + + @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': [ + Triangle, + Quadrilateral, + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..b1a7ecd967d1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/shape_or_null.py @@ -0,0 +1,125 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + _discriminator(cls) -> dict: the key is the required discriminator propertyName + the value is a dict mapping from a string name to the corresponding Schema class + """ + + @classmethod + @property + def _discriminator(cls): + return { + 'shapeType': { + 'Quadrilateral': Quadrilateral, + 'Triangle': Triangle, + } + } + + @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 + oneOf_0 = NoneSchema + return { + 'allOf': [ + ], + 'oneOf': [ + oneOf_0, + Triangle, + Quadrilateral, + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..bc907bfb30b5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/simple_quadrilateral.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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': [ + QuadrilateralInterface, + SimpleQuadrilateralAllOf, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + +from petstore_api.model.quadrilateral_interface import QuadrilateralInterface +from petstore_api.model.simple_quadrilateral_all_of import SimpleQuadrilateralAllOf diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model/simple_quadrilateral_all_of.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/simple_quadrilateral_all_of.py new file mode 100644 index 000000000000..b6b63fb9ff04 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/simple_quadrilateral_all_of.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class SimpleQuadrilateralAllOf( + DictSchema +): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + quadrilateralType (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + + class quadrilateralType( + _SchemaEnumMaker( + enum_value_to_name={ + "SimpleQuadrilateral": "SIMPLEQUADRILATERAL", + } + ), + StrSchema + ): + + @classmethod + @property + def SIMPLEQUADRILATERAL(cls): + return cls._enum_by_value["SimpleQuadrilateral"]("SimpleQuadrilateral") + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + quadrilateralType: typing.Union[quadrilateralType, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + quadrilateralType=quadrilateralType, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) 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 new file mode 100644 index 000000000000..c4fa2a0cff63 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/some_object.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + + @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': [ + ObjectInterface, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..47c8e538244d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/special_model_name.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 re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 + + Attributes: + a (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + a = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + a: typing.Union[a, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + a=a, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..9b51e661bfde --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string.py @@ -0,0 +1,59 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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 new file mode 100644 index 000000000000..8022c91ced12 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_boolean_map.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _additional_properties = BoolSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..0f803ec7d242 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_enum.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _SchemaValidator, + _SchemaTypeChecker, + _SchemaEnumMaker +) + + +class StringEnum( + _SchemaTypeChecker(typing.Union[none_type, str, ]), + _SchemaEnumMaker( + enum_value_to_name={ + None: "NONE", + "placed": "PLACED", + "approved": "APPROVED", + "delivered": "DELIVERED", + "single quoted": "SINGLE_QUOTED", + '''multiple +lines''': "MULTIPLE_LINES", + '''double quote + 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. + + Attributes: + """ + + @classmethod + @property + def NONE(cls): + return cls._enum_by_value[None](None) + + @classmethod + @property + def PLACED(cls): + return cls._enum_by_value["placed"]("placed") + + @classmethod + @property + def APPROVED(cls): + return cls._enum_by_value["approved"]("approved") + + @classmethod + @property + def DELIVERED(cls): + return cls._enum_by_value["delivered"]("delivered") + + @classmethod + @property + def SINGLE_QUOTED(cls): + return cls._enum_by_value["single quoted"]("single quoted") + + @classmethod + @property + def MULTIPLE_LINES(cls): + return cls._enum_by_value['''multiple +lines''']('''multiple +lines''') + + @classmethod + @property + def DOUBLE_QUOTE_WITH_NEWLINE(cls): + return cls._enum_by_value['''double quote + with newline''']('''double quote + with newline''') + + def __new__( + cls, + *args: typing.Union[str, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + ) 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 new file mode 100644 index 000000000000..7894c4093a43 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_enum_with_default_value.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 re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + """ + + @classmethod + @property + def PLACED(cls): + return cls._enum_by_value["placed"]("placed") + + @classmethod + @property + def APPROVED(cls): + return cls._enum_by_value["approved"]("approved") + + @classmethod + @property + def DELIVERED(cls): + return cls._enum_by_value["delivered"]("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 new file mode 100644 index 000000000000..135b181127db --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/string_with_validation.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _validations (dict): the validations which apply to the current Schema + 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. + """ + 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 new file mode 100644 index 000000000000..275974b2ecf3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/tag.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + id (int,): + name (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + id = Int64Schema + name = StrSchema + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + id: typing.Union[id, Unset] = unset, + name: typing.Union[name, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + id=id, + name=name, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..a35af496f9c2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/triangle.py @@ -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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + _discriminator(cls) -> dict: the key is the required discriminator propertyName + the value is a dict mapping from a string name to the corresponding Schema class + """ + + @classmethod + @property + def _discriminator(cls): + return { + 'triangleType': { + 'EquilateralTriangle': EquilateralTriangle, + 'IsoscelesTriangle': IsoscelesTriangle, + 'ScaleneTriangle': ScaleneTriangle, + } + } + + @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': [ + EquilateralTriangle, + IsoscelesTriangle, + ScaleneTriangle, + ], + 'anyOf': [ + ], + } + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..d21d93687c8e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/triangle_interface.py @@ -0,0 +1,111 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + shapeType (str,): + triangleType (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _required_property_names = set(( + 'shapeType', + 'triangleType', + )) + + + class shapeType( + _SchemaEnumMaker( + enum_value_to_name={ + "Triangle": "TRIANGLE", + } + ), + StrSchema + ): + + @classmethod + @property + def TRIANGLE(cls): + return cls._enum_by_value["Triangle"]("Triangle") + triangleType = StrSchema + + def __new__( + cls, + *args: typing.Union[dict, frozendict, str, date, datetime, int, float, Decimal, None, list, tuple, bytes], + shapeType: shapeType, + triangleType: triangleType, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + shapeType=shapeType, + triangleType=triangleType, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..dccbf4d2040e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/user.py @@ -0,0 +1,154 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + id (int,): + username (str,): + firstName (str,): + lastName (str,): + email (str,): + password (str,): + phone (str,): + userStatus (int,): User Status + objectWithNoDeclaredProps (dict,): test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + objectWithNoDeclaredPropsNullable (dict, none_type,): test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + anyTypeProp (): 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 (): 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. + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + id = Int64Schema + username = StrSchema + firstName = StrSchema + lastName = StrSchema + email = StrSchema + password = StrSchema + phone = StrSchema + userStatus = Int32Schema + objectWithNoDeclaredProps = DictSchema + + + class objectWithNoDeclaredPropsNullable( + _SchemaTypeChecker(typing.Union[frozendict, none_type, ]), + DictBase, + NoneBase, + Schema + ): + + def __new__( + cls, + *args: typing.Union[dict, frozendict, None, ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) + anyTypeProp = AnyTypeSchema + 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, + anyTypePropNullable: typing.Union[anyTypePropNullable, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + 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, + anyTypePropNullable=anyTypePropNullable, + _instantiation_metadata=_instantiation_metadata, + **kwargs, + ) 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 new file mode 100644 index 000000000000..2018c62eb3c2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/whale.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 re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + hasBaleen (bool,): + hasTeeth (bool,): + className (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _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._enum_by_value["whale"]("whale") + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + className: className, + hasBaleen: typing.Union[hasBaleen, Unset] = unset, + hasTeeth: typing.Union[hasTeeth, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + className=className, + hasBaleen=hasBaleen, + hasTeeth=hasTeeth, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..8a5ef4550d78 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model/zebra.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 +""" + +import re # noqa: F401 +import sys # noqa: F401 +import typing # noqa: F401 + +from frozendict import frozendict # noqa: F401 + +from decimal 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, + DateSchema, + DateTimeSchema, + BoolSchema, + BinarySchema, + NoneSchema, + none_type, + InstantiationMetadata, + Unset, + unset, + ComposedBase, + ListBase, + DictBase, + NoneBase, + StrBase, + IntBase, + NumberBase, + DateBase, + DateTimeBase, + BoolBase, + BinaryBase, + Schema, + _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. + + Attributes: + type (str,): + className (str,): + _additional_properties (Schema): the definition used for additional properties + that are not defined in _properties + """ + _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._enum_by_value["plains"]("plains") + + @classmethod + @property + def MOUNTAIN(cls): + return cls._enum_by_value["mountain"]("mountain") + + @classmethod + @property + def GREVYS(cls): + return cls._enum_by_value["grevys"]("grevys") + + + class className( + _SchemaEnumMaker( + enum_value_to_name={ + "zebra": "ZEBRA", + } + ), + StrSchema + ): + + @classmethod + @property + def ZEBRA(cls): + return cls._enum_by_value["zebra"]("zebra") + + + def __new__( + cls, + *args: typing.Union[dict, frozendict, ], + className: className, + type: typing.Union[type, Unset] = unset, + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Type[Schema], + ): + return super().__new__( + cls, + *args, + className=className, + type=type, + _instantiation_metadata=_instantiation_metadata, + **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 new file mode 100644 index 000000000000..9d3b94558c88 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/__init__.py @@ -0,0 +1,126 @@ +# 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.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.complex_quadrilateral_all_of import ComplexQuadrilateralAllOf +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.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.dog import Dog +from petstore_api.model.dog_all_of import DogAllOf +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.equilateral_triangle_all_of import EquilateralTriangleAllOf +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.inline_response_default import InlineResponseDefault +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.isosceles_triangle_all_of import IsoscelesTriangleAllOf +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.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_difficultly_named_props import ObjectWithDifficultlyNamedProps +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.scalene_triangle_all_of import ScaleneTriangleAllOf +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.simple_quadrilateral_all_of import SimpleQuadrilateralAllOf +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.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 new file mode 100644 index 000000000000..7724b98a71c2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/rest.py @@ -0,0 +1,258 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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, + query_params: typing.Optional[typing.Tuple[typing.Tuple[str, str], ...]] = None, + 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 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]) + + if 'Content-Type' not in headers: + headers['Content-Type'] = 'application/json' + + try: + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + if query_params: + url += '?' + urlencode(query_params) + if 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, + fields=query_params, + 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, query_params=None, stream=False, + timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("GET", url, + headers=headers, + stream=stream, + timeout=timeout, + query_params=query_params, fields=fields) + + def HEAD(self, url, headers=None, query_params=None, stream=False, + timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("HEAD", url, + headers=headers, + stream=stream, + timeout=timeout, + query_params=query_params, fields=fields) + + def OPTIONS(self, url, headers=None, query_params=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("OPTIONS", url, + headers=headers, + query_params=query_params, + stream=stream, + timeout=timeout, + body=body, fields=fields) + + def DELETE(self, url, headers=None, query_params=None, body=None, + stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("DELETE", url, + headers=headers, + query_params=query_params, + stream=stream, + timeout=timeout, + body=body, fields=fields) + + def POST(self, url, headers=None, query_params=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("POST", url, + headers=headers, + query_params=query_params, + stream=stream, + timeout=timeout, + body=body, fields=fields) + + def PUT(self, url, headers=None, query_params=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("PUT", url, + headers=headers, + query_params=query_params, + stream=stream, + timeout=timeout, + body=body, fields=fields) + + def PATCH(self, url, headers=None, query_params=None, + body=None, stream=False, timeout=None, fields=None) -> urllib3.HTTPResponse: + return self.request("PATCH", url, + headers=headers, + query_params=query_params, + 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 new file mode 100644 index 000000000000..e230675efaa9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/schemas.py @@ -0,0 +1,1994 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use 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 +from dataclasses import dataclass +import functools +from decimal import Decimal +import io +import os +import re +import tempfile +import typing + +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)): + 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 update(d: dict, u: dict): + """ + Adds u to d + Where each dict is defaultdict(set) + """ + for k, v in u.items(): + d[k] = d[k].union(v) + return d + + +class InstantiationMetadata: + """ + A class to store metadata that is needed when instantiating OpenApi Schema subclasses + """ + def __init__( + self, + path_to_item: typing.Tuple[typing.Union[str, int], ...] = tuple(['args[0]']), + from_server: bool = False, + configuration: typing.Optional[Configuration] = None, + base_classes: typing.FrozenSet[typing.Type] = frozenset(), + path_to_schemas: typing.Optional[typing.Dict[str, typing.Set[typing.Type]]] = None, + ): + """ + 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) + 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 + configuration: the Configuration instance to use + This is needed because in Configuration: + - one can disable validation checking + base_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. + path_to_schemas: a dict that goes from path to a list of classes at each path location + """ + self.path_to_item = path_to_item + self.from_server = from_server + self.configuration = configuration + self.base_classes = base_classes + if path_to_schemas is None: + path_to_schemas = defaultdict(set) + self.path_to_schemas = path_to_schemas + + def __repr__(self): + return str(self.__dict__) + + def __eq__(self, other): + if not isinstance(other, InstantiationMetadata): + return False + return self.__dict__ == other.__dict__ + + +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, + _instantiation_metadata: InstantiationMetadata): + + if (cls.__is_json_validation_enabled('maxLength', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('minLength', _instantiation_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=_instantiation_metadata.path_to_item + ) + + checked_value = input_values + if (cls.__is_json_validation_enabled('pattern', _instantiation_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=_instantiation_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=_instantiation_metadata.path_to_item + ) + + @classmethod + def __check_tuple_validations( + cls, validations, input_values, + _instantiation_metadata: InstantiationMetadata): + + if (cls.__is_json_validation_enabled('maxItems', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('minItems', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('uniqueItems', _instantiation_metadata.configuration) and + 'unique_items' in validations and validations['unique_items'] and input_values): + unique_items = [] + # print(validations) + for item in input_values: + if item not in unique_items: + unique_items.append(item) + 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=_instantiation_metadata.path_to_item + ) + + @classmethod + def __check_dict_validations( + cls, validations, input_values, + _instantiation_metadata: InstantiationMetadata): + + if (cls.__is_json_validation_enabled('maxProperties', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('minProperties', _instantiation_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=_instantiation_metadata.path_to_item + ) + + @classmethod + def __check_numeric_validations( + cls, validations, input_values, + _instantiation_metadata: InstantiationMetadata): + + if cls.__is_json_validation_enabled('multipleOf', + _instantiation_metadata.configuration) and 'multiple_of' in validations: + multiple_of_values = validations['multiple_of'] + for multiple_of_value in multiple_of_values: + if (isinstance(input_values, 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=_instantiation_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', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('maximum', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('exclusiveMinimum', _instantiation_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=_instantiation_metadata.path_to_item + ) + + if (cls.__is_json_validation_enabled('minimum', _instantiation_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=_instantiation_metadata.path_to_item + ) + + @classmethod + def _check_validations_for_types( + cls, + validations, + input_values, + _instantiation_metadata: InstantiationMetadata + ): + if isinstance(input_values, str): + cls.__check_str_validations(validations, input_values, _instantiation_metadata) + elif isinstance(input_values, tuple): + cls.__check_tuple_validations(validations, input_values, _instantiation_metadata) + elif isinstance(input_values, frozendict): + cls.__check_dict_validations(validations, input_values, _instantiation_metadata) + elif isinstance(input_values, Decimal): + cls.__check_numeric_validations(validations, input_values, _instantiation_metadata) + try: + return super()._validate_validations_pass(input_values, _instantiation_metadata) + except AttributeError: + return True + + +class Validator(typing.Protocol): + def _validate_validations_pass( + cls, + input_values, + _instantiation_metadata: InstantiationMetadata + ): + 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_validations_pass( + cls, + input_values, + _instantiation_metadata: InstantiationMetadata + ): + cls._check_validations_for_types(validations, input_values, _instantiation_metadata) + try: + return super()._validate_validations_pass(input_values, _instantiation_metadata) + except AttributeError: + return True + + return SchemaValidator + + +class TypeChecker(typing.Protocol): + @classmethod + def _validate_type( + cls, arg_simple_class: type + ) -> typing.Tuple[type]: + pass + + +def _SchemaTypeChecker(union_type_cls: typing.Union[typing.Any]) -> TypeChecker: + 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: + @classmethod + def _validate_type(cls, arg_simple_class: type): + if arg_simple_class not in union_classes: + return union_classes + try: + return super()._validate_type(arg_simple_class) + except AttributeError: + return tuple() + + return SchemaTypeChecker + + +class EnumMakerBase: + @classmethod + @property + def _enum_by_value( + cls + ) -> type: + enum_classes = {} + if not hasattr(cls, "_enum_value_to_name"): + return enum_classes + for enum_value, enum_name in cls._enum_value_to_name.items(): + base_class = type(enum_value) + if base_class is none_type: + enum_classes[enum_value] = get_new_class( + "Dynamic" + cls.__name__, (cls, NoneClass)) + log_cache_usage(get_new_class) + elif base_class is bool: + enum_classes[enum_value] = get_new_class( + "Dynamic" + cls.__name__, (cls, BoolClass)) + log_cache_usage(get_new_class) + else: + enum_classes[enum_value] = get_new_class( + "Dynamic" + cls.__name__, (cls, Singleton, base_class)) + log_cache_usage(get_new_class) + return enum_classes + + +class EnumMakerInterface(typing.Protocol): + @classmethod + @property + def _enum_value_to_name( + cls + ) -> typing.Dict[typing.Union[str, Decimal, bool, none_type], str]: + pass + + @classmethod + @property + def _enum_by_value( + cls + ) -> type: + pass + + +def _SchemaEnumMaker(enum_value_to_name: typing.Dict[typing.Union[str, Decimal, bool, none_type], str]) -> EnumMakerInterface: + class SchemaEnumMaker(EnumMakerBase): + @classmethod + @property + def _enum_value_to_name( + cls + ) -> typing.Dict[typing.Union[str, 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 + + return SchemaEnumMaker + + +class Singleton: + """ + Enums and singletons are the same + The same instance is returned for a given key of (cls, arg) + """ + # TODO use bidict to store this so boolean enums can move through it in reverse to get their own arg value? + _instances = {} + + def __new__(cls, *args, **kwargs): + if not args: + raise ValueError('arg must be passed') + arg = args[0] + key = (cls, arg) + if key not in cls._instances: + if arg in {None, True, False}: + inst = super().__new__(cls) + # inst._value = arg + cls._instances[key] = inst + else: + cls._instances[key] = super().__new__(cls, arg) + return cls._instances[key] + + def __repr__(self): + return '({}, {})'.format(self.__class__.__name__, self) + + +class NoneClass(Singleton): + @classmethod + @property + def NONE(cls): + return cls(None) + + def is_none(self) -> bool: + return True + + 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 key[1] + raise ValueError('Unable to find the boolean value of this instance') + + def is_true(self): + return bool(self) + + def is_false(self): + return bool(self) + + +class BoolBase: + pass + + +class NoneBase: + pass + + +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') + + +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], _instantiation_metadata: InstantiationMetadata): + 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, _instantiation_metadata.path_to_item) + ) + + @classmethod + def _validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + DateBase _validate + """ + cls._validate_format(args[0], _instantiation_metadata=_instantiation_metadata) + return super()._validate(*args, _instantiation_metadata=_instantiation_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], _instantiation_metadata: InstantiationMetadata): + 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, _instantiation_metadata.path_to_item) + ) + + @classmethod + def _validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + DateTimeBase _validate + """ + cls._validate_format(args[0], _instantiation_metadata=_instantiation_metadata) + return super()._validate(*args, _instantiation_metadata=_instantiation_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, _instantiation_metadata: InstantiationMetadata): + """ + 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 = defaultdict(set) + for i, value in enumerate(list_items): + if isinstance(value, item_cls): + continue + item_instantiation_metadata = InstantiationMetadata( + from_server=_instantiation_metadata.from_server, + configuration=_instantiation_metadata.configuration, + path_to_item=_instantiation_metadata.path_to_item+(i,) + ) + other_path_to_schemas = item_cls._validate( + value, _instantiation_metadata=item_instantiation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def _validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + 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 + """ + arg = args[0] + _path_to_schemas = super()._validate(*args, _instantiation_metadata=_instantiation_metadata) + if not isinstance(arg, tuple): + return _path_to_schemas + if cls in _instantiation_metadata.base_classes: + # we have already moved through this class so stop here + return _path_to_schemas + _instantiation_metadata.base_classes |= frozenset({cls}) + other_path_to_schemas = cls._validate_items(arg, _instantiation_metadata=_instantiation_metadata) + update(_path_to_schemas, other_path_to_schemas) + return _path_to_schemas + + @classmethod + def _get_items(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + ''' + ListBase _get_items + ''' + _instantiation_metadata = InstantiationMetadata() if _instantiation_metadata is None else _instantiation_metadata + + list_items = args[0] + 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 = _instantiation_metadata.path_to_item+(i,) + if item_path_to_item in _instantiation_metadata.path_to_schemas: + item_cls = _instantiation_metadata.path_to_schemas[item_path_to_item] + else: + item_cls = cls_item_cls + + if isinstance(value, item_cls): + cast_items.append(value) + continue + item_instantiation_metadata = InstantiationMetadata( + configuration=_instantiation_metadata.configuration, + from_server=_instantiation_metadata.from_server, + path_to_item=item_path_to_item, + path_to_schemas=_instantiation_metadata.path_to_schemas, + ) + + if _instantiation_metadata.from_server: + new_value = item_cls._from_openapi_data(value, _instantiation_metadata=item_instantiation_metadata) + else: + new_value = item_cls(value, _instantiation_metadata=item_instantiation_metadata) + cast_items.append(new_value) + + return cast_items + + +class Discriminable: + @classmethod + def _ensure_discriminator_value_present(cls, disc_property_name: str, _instantiation_metadata: InstantiationMetadata, *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, _instantiation_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, _instantiation_metadata: InstantiationMetadata): + """ + 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 = defaultdict(set) + 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, _instantiation_metadata.path_to_item+(property_name,) + )) + if isinstance(value, schema): + continue + arg_instantiation_metadata = InstantiationMetadata( + from_server=_instantiation_metadata.from_server, + configuration=_instantiation_metadata.configuration, + path_to_item=_instantiation_metadata.path_to_item+(property_name,) + ) + other_path_to_schemas = schema._validate(value, _instantiation_metadata=arg_instantiation_metadata) + update(path_to_schemas, other_path_to_schemas) + _instantiation_metadata.path_to_schemas.update(arg_instantiation_metadata.path_to_schemas) + return path_to_schemas + + @classmethod + def _validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + 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 args and isinstance(args[0], cls): + # an instance of the correct type was passed in + return {} + arg = args[0] + _path_to_schemas = super()._validate(*args, _instantiation_metadata=_instantiation_metadata) + if not isinstance(arg, frozendict): + return _path_to_schemas + cls._validate_arg_presence(args[0]) + other_path_to_schemas = cls._validate_args(args[0], _instantiation_metadata=_instantiation_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, _instantiation_metadata, *args) + 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()), + _instantiation_metadata.path_to_item + (disc_prop_name,) + ) + ) + if discriminated_cls in _instantiation_metadata.base_classes: + # we have already moved through this class so stop here + return _path_to_schemas + _instantiation_metadata.base_classes |= frozenset({cls}) + other_path_to_schemas = discriminated_cls._validate(*args, _instantiation_metadata=_instantiation_metadata) + 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], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + 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 + + _instantiation_metadata = InstantiationMetadata() if _instantiation_metadata is None else _instantiation_metadata + + for property_name_js, value in arg.items(): + property_cls = getattr(cls, property_name_js, cls._additional_properties) + property_path_to_item = _instantiation_metadata.path_to_item+(property_name_js,) + stored_property_cls = _instantiation_metadata.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 + + prop_instantiation_metadata = InstantiationMetadata( + configuration=_instantiation_metadata.configuration, + from_server=_instantiation_metadata.from_server, + path_to_item=property_path_to_item, + path_to_schemas=_instantiation_metadata.path_to_schemas, + ) + if _instantiation_metadata.from_server: + new_value = property_cls._from_openapi_data(value, _instantiation_metadata=prop_instantiation_metadata) + else: + new_value = property_cls(value, _instantiation_metadata=prop_instantiation_metadata) + 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)) + # print(('non-frozendict __getattr__', name)) + return super().__getattr__(self, name) + + def __getattribute__(self, name): + # print(('__getattribute__', 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, str, tuple, frozendict, FileIO, bytes} + + +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 + """ + + @staticmethod + def __get_simple_class(input_value): + """Returns an input_value's simple class that we will use for type checking + + Args: + input_value (class/class_instance): the item for which we will return + the simple class + """ + if isinstance(input_value, tuple): + return tuple + elif isinstance(input_value, frozendict): + return frozendict + elif isinstance(input_value, none_type): + return none_type + elif isinstance(input_value, bytes): + return bytes + elif isinstance(input_value, (io.FileIO, io.BufferedReader)): + return FileIO + 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, float): + return float + 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) + + @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 _class_by_base_class(cls, base_cls: type) -> type: + cls_name = "Dynamic"+cls.__name__ + if base_cls is bool: + new_cls = get_new_class(cls_name, (cls, BoolBase, BoolClass)) + elif base_cls is str: + new_cls = get_new_class(cls_name, (cls, StrBase, str)) + elif base_cls is Decimal: + new_cls = get_new_class(cls_name, (cls, NumberBase, Decimal)) + elif base_cls is tuple: + new_cls = get_new_class(cls_name, (cls, ListBase, tuple)) + elif base_cls is frozendict: + new_cls = get_new_class(cls_name, (cls, DictBase, frozendict)) + elif base_cls is none_type: + new_cls = get_new_class(cls_name, (cls, NoneBase, NoneClass)) + log_cache_usage(get_new_class) + return new_cls + + @classmethod + def _validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + 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/frozendict/tuple + 2. enum value cases: 'hi', 1 -> no base_class set because the enum includes the base class + 3. uninheritable type: True/False/None -> no base_class because the base class is not inheritable + _enum_by_value will handle this use case + + 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 + """ + arg = args[0] + + base_class = cls.__get_simple_class(arg) + failed_type_check_classes = cls._validate_type(base_class) + if failed_type_check_classes: + raise cls.__get_type_error( + arg, + _instantiation_metadata.path_to_item, + failed_type_check_classes, + key_type=False, + ) + if hasattr(cls, '_validate_validations_pass'): + cls._validate_validations_pass(arg, _instantiation_metadata) + path_to_schemas = defaultdict(set) + path_to_schemas[_instantiation_metadata.path_to_item].add(cls) + + if hasattr(cls, "_enum_by_value"): + cls._validate_enum_value(arg) + return path_to_schemas + + if base_class is none_type or base_class is bool: + return path_to_schemas + + path_to_schemas[_instantiation_metadata.path_to_item].add(base_class) + return path_to_schemas + + @classmethod + def _validate_enum_value(cls, arg): + try: + cls._enum_by_value[arg] + except KeyError: + raise ApiValueError("Invalid value {} passed in to {}, {}".format(arg, cls, cls._enum_value_to_name)) + + @classmethod + def __get_new_cls(cls, arg, _instantiation_metadata: InstantiationMetadata): + """ + PATH 1 - 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 + """ + if ( + _instantiation_metadata.path_to_schemas and + _instantiation_metadata.path_to_item in _instantiation_metadata.path_to_schemas): + chosen_new_cls = _instantiation_metadata.path_to_schemas[_instantiation_metadata.path_to_item] + # print('leaving __get_new_cls early for cls {} because path_to_schemas exists'.format(cls)) + # print(_instantiation_metadata.path_to_item) + # print(chosen_new_cls) + return chosen_new_cls + """ + 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 = cls._validate(arg, _instantiation_metadata=_instantiation_metadata) + from pprint import pprint + pprint(dict(_path_to_schemas)) + # loop through it make a new class for each entry + for path, schema_classes in _path_to_schemas.items(): + enum_schema = any( + hasattr(this_cls, '_enum_by_value') for this_cls in schema_classes) + inheritable_primitive_type = schema_classes.intersection(inheritable_primitive_types_set) + chosen_schema_classes = schema_classes + suffix = tuple() + if inheritable_primitive_type: + chosen_schema_classes = schema_classes - inheritable_primitive_types_set + if not enum_schema: + # include the inheritable_primitive_type + suffix = tuple(inheritable_primitive_type) + + if len(chosen_schema_classes) == 1 and not suffix: + mfg_cls = tuple(chosen_schema_classes)[0] + else: + x_schema = schema_descendents & chosen_schema_classes + if x_schema: + x_schema = x_schema.pop() + if any(c is not x_schema and issubclass(c, x_schema) for c in chosen_schema_classes): + # needed to not have a mro error in get_new_class + chosen_schema_classes.remove(x_schema) + 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) + + if inheritable_primitive_type and not enum_schema: + _instantiation_metadata.path_to_schemas[path] = mfg_cls + continue + + # Use case: value is None, True, False, or an enum value + # print('choosing enum class for path {} in arg {}'.format(path, arg)) + value = arg + for key in path[1:]: + value = value[key] + if hasattr(mfg_cls, '_enum_by_value'): + mfg_cls = mfg_cls._enum_by_value[value] + elif value in {True, False}: + mfg_cls = mfg_cls._class_by_base_class(bool) + elif value is None: + mfg_cls = mfg_cls._class_by_base_class(none_type) + else: + raise ApiValueError('Unhandled case value={} bases={}'.format(value, mfg_cls.__bases__)) + _instantiation_metadata.path_to_schemas[path] = mfg_cls + + return _instantiation_metadata.path_to_schemas[_instantiation_metadata.path_to_item] + + @classmethod + def __get_new_instance_without_conversion(cls, arg, _instantiation_metadata): + # PATH 2 - we have a Dynamic class and we are making an instance of it + if issubclass(cls, tuple): + items = cls._get_items(arg, _instantiation_metadata=_instantiation_metadata) + return super(Schema, cls).__new__(cls, items) + elif issubclass(cls, frozendict): + properties = cls._get_properties(arg, _instantiation_metadata=_instantiation_metadata) + return super(Schema, cls).__new__(cls, properties) + """ + str = openapi str, date, and datetime + 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, + bool, + None, + 'Schema', + dict, + frozendict, + tuple, + list, + io.FileIO, + io.BufferedReader, + bytes + ], + _instantiation_metadata: typing.Optional[InstantiationMetadata] + ): + arg = cast_to_allowed_types(arg, from_server=True) + _instantiation_metadata = InstantiationMetadata(from_server=True) if _instantiation_metadata is None else _instantiation_metadata + if not _instantiation_metadata.from_server: + raise ApiValueError( + 'from_server must be True in this code path, if you need it to be False, use cls()' + ) + new_cls = cls.__get_new_cls(arg, _instantiation_metadata) + new_inst = new_cls.__get_new_instance_without_conversion(arg, _instantiation_metadata) + 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, float, int, str, date, datetime, bool, None, 'Schema'], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, **kwargs: typing.Union[dict, frozendict, list, tuple, Decimal, float, int, str, date, datetime, bool, None, 'Schema', Unset]): + """ + Schema __new__ + + Args: + args (int/float/Decimal/str/list/tuple/dict/frozendict/bool/None): the value + kwargs (str, int/float/Decimal/str/list/tuple/dict/frozendict/bool/None): dict values + _instantiation_metadata: contains the needed from_server, configuration, path_to_item + """ + 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) + _instantiation_metadata = InstantiationMetadata() if _instantiation_metadata is None else _instantiation_metadata + if _instantiation_metadata.from_server: + raise ApiValueError( + 'from_server must be False in this code path, if you need it to be True, use cls._from_openapi_data()' + ) + arg = cast_to_allowed_types(arg, from_server=_instantiation_metadata.from_server) + new_cls = cls.__get_new_cls(arg, _instantiation_metadata) + return new_cls.__get_new_instance_without_conversion(arg, _instantiation_metadata) + + def __init__( + self, + *args: typing.Union[ + dict, frozendict, list, tuple, Decimal, float, int, str, date, datetime, bool, None, 'Schema'], + _instantiation_metadata: typing.Optional[InstantiationMetadata] = None, + **kwargs: typing.Union[ + dict, frozendict, list, tuple, 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, int, float, None, dict, frozendict, list, tuple, bytes, Schema], from_server=False) -> typing.Union[str, bytes, int, float, None, frozendict, tuple, Schema]: + """ + from_server=False date, datetime -> str + int, float -> Decimal + StrSchema will convert that to bytes and remember the encoding when we pass in str input + """ + if isinstance(arg, (date, datetime)): + if not from_server: + return arg.isoformat() + # ApiTypeError will be thrown later by _validate_type + return arg + elif isinstance(arg, bool): + """ + this check must come before isinstance(arg, (int, float)) + because isinstance(True, int) is True + """ + return arg + elif isinstance(arg, Decimal): + return arg + elif isinstance(arg, int): + return Decimal(arg) + elif isinstance(arg, float): + decimal_from_float = Decimal(arg) + if decimal_from_float.as_integer_ratio()[1] == 1: + # 9.0 -> Decimal('9.0') + # 3.4028234663852886e+38 -> Decimal('340282346638528859811704183484516925440.0') + return Decimal(str(decimal_from_float)+'.0') + return decimal_from_float + elif isinstance(arg, str): + return arg + elif isinstance(arg, bytes): + return arg + elif isinstance(arg, (io.FileIO, io.BufferedReader)): + if arg.closed: + raise ApiValueError('Invalid file state; file is closed and must be open') + return arg + elif type(arg) is list or type(arg) is tuple: + return tuple([cast_to_allowed_types(item) for item in arg]) + elif type(arg) is dict or type(arg) is frozendict: + return frozendict({key: cast_to_allowed_types(val) for key, val in arg.items() if val is not unset}) + elif arg is None: + return arg + elif isinstance(arg, Schema): + return arg + raise ValueError('Invalid type passed in got input={} type={}'.format(arg, type(arg))) + + +class ComposedBase(Discriminable): + + @classmethod + def __get_allof_classes(cls, *args, _instantiation_metadata: InstantiationMetadata): + path_to_schemas = defaultdict(set) + for allof_cls in cls._composed_schemas['allOf']: + if allof_cls in _instantiation_metadata.base_classes: + continue + other_path_to_schemas = allof_cls._validate(*args, _instantiation_metadata=_instantiation_metadata) + update(path_to_schemas, other_path_to_schemas) + return path_to_schemas + + @classmethod + def __get_oneof_class( + cls, + *args, + discriminated_cls, + _instantiation_metadata: InstantiationMetadata, + path_to_schemas: typing.Dict[typing.Tuple, typing.Set[typing.Type[Schema]]] + ): + oneof_classes = [] + chosen_oneof_cls = None + original_base_classes = _instantiation_metadata.base_classes + new_base_classes = _instantiation_metadata.base_classes + path_to_schemas = defaultdict(set) + for oneof_cls in cls._composed_schemas['oneOf']: + if oneof_cls in path_to_schemas[_instantiation_metadata.path_to_item]: + oneof_classes.append(oneof_cls) + continue + if isinstance(args[0], oneof_cls): + # passed in instance is the correct type + chosen_oneof_cls = oneof_cls + oneof_classes.append(oneof_cls) + continue + _instantiation_metadata.base_classes = original_base_classes + try: + path_to_schemas = oneof_cls._validate(*args, _instantiation_metadata=_instantiation_metadata) + new_base_classes = _instantiation_metadata.base_classes + except (ApiValueError, ApiTypeError) as ex: + if discriminated_cls is not None and oneof_cls is discriminated_cls: + raise ex + continue + chosen_oneof_cls = oneof_cls + 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) + ) + _instantiation_metadata.base_classes = new_base_classes + return path_to_schemas + + @classmethod + def __get_anyof_classes( + cls, + *args, + discriminated_cls, + _instantiation_metadata: InstantiationMetadata + ): + anyof_classes = [] + chosen_anyof_cls = None + original_base_classes = _instantiation_metadata.base_classes + path_to_schemas = defaultdict(set) + for anyof_cls in cls._composed_schemas['anyOf']: + if anyof_cls in _instantiation_metadata.base_classes: + continue + if isinstance(args[0], anyof_cls): + # passed in instance is the correct type + chosen_anyof_cls = anyof_cls + anyof_classes.append(anyof_cls) + continue + + _instantiation_metadata.base_classes = original_base_classes + try: + other_path_to_schemas = anyof_cls._validate(*args, _instantiation_metadata=_instantiation_metadata) + except (ApiValueError, ApiTypeError) as ex: + if discriminated_cls is not None and anyof_cls is discriminated_cls: + raise ex + continue + original_base_classes = _instantiation_metadata.base_classes + chosen_anyof_cls = anyof_cls + 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, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + 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 args and isinstance(args[0], Schema) and _instantiation_metadata.from_server is False: + if isinstance(args[0], 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(args[0]), + _instantiation_metadata.path_to_item + ) + ) + + # validation checking on types, validations, and enums + path_to_schemas = super()._validate(*args, _instantiation_metadata=_instantiation_metadata) + + _instantiation_metadata.base_classes |= frozenset({cls}) + + # process composed schema + _discriminator = getattr(cls, '_discriminator', None) + discriminated_cls = None + if _discriminator and args and isinstance(args[0], frozendict): + disc_property_name = list(_discriminator.keys())[0] + cls._ensure_discriminator_value_present(disc_property_name, _instantiation_metadata, *args) + # 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=args[0][disc_property_name]) + if discriminated_cls is None: + raise ApiValueError( + "Invalid discriminator value '{}' was passed in to {}.{} Only the values {} are allowed at {}".format( + args[0][disc_property_name], + cls.__name__, + disc_property_name, + list(_discriminator[disc_property_name].keys()), + _instantiation_metadata.path_to_item + (disc_property_name,) + ) + ) + + if cls._composed_schemas['allOf']: + other_path_to_schemas = cls.__get_allof_classes(*args, _instantiation_metadata=_instantiation_metadata) + update(path_to_schemas, other_path_to_schemas) + if cls._composed_schemas['oneOf']: + other_path_to_schemas = cls.__get_oneof_class( + *args, + discriminated_cls=discriminated_cls, + _instantiation_metadata=_instantiation_metadata, + 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( + *args, + discriminated_cls=discriminated_cls, + _instantiation_metadata=_instantiation_metadata + ) + update(path_to_schemas, other_path_to_schemas) + + if discriminated_cls is not None: + # TODO use an exception from this package here + assert discriminated_cls in path_to_schemas[_instantiation_metadata.path_to_item] + return path_to_schemas + + +# DictBase, ListBase, NumberBase, StrBase, BoolBase, NoneBase +class ComposedSchema( + _SchemaTypeChecker(typing.Union[none_type, str, Decimal, bool, tuple, frozendict]), + ComposedBase, + DictBase, + ListBase, + NumberBase, + StrBase, + BoolBase, + NoneBase, + Schema +): + + # subclass properties + _composed_schemas = {} + + @classmethod + def _from_openapi_data(cls, *args: typing.Any, _instantiation_metadata: typing.Optional[InstantiationMetadata] = 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], _instantiation_metadata=_instantiation_metadata) + + +class ListSchema( + _SchemaTypeChecker(typing.Union[tuple]), + ListBase, + Schema +): + + @classmethod + def _from_openapi_data(cls, arg: typing.List[typing.Any], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, arg: typing.Union[list, tuple], **kwargs: InstantiationMetadata): + return super().__new__(cls, arg, **kwargs) + + +class NoneSchema( + _SchemaTypeChecker(typing.Union[none_type]), + NoneBase, + Schema +): + + @classmethod + def _from_openapi_data(cls, arg: None, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, arg: None, **kwargs: typing.Union[InstantiationMetadata]): + return super().__new__(cls, arg, **kwargs) + + +class NumberSchema( + _SchemaTypeChecker(typing.Union[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], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, arg: typing.Union[Decimal, int, float], **kwargs: typing.Union[InstantiationMetadata]): + 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], _instantiation_metadata: InstantiationMetadata): + if isinstance(arg, Decimal): + exponent = arg.as_tuple().exponent + if exponent != 0: + raise ApiValueError( + "Invalid value '{}' for type integer at {}".format(arg, _instantiation_metadata.path_to_item) + ) + + @classmethod + def _validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + """ + IntBase _validate + TODO what about types = (int, number) -> IntBase, NumberBase? We could drop int and keep number only + """ + cls._validate_format(args[0], _instantiation_metadata=_instantiation_metadata) + return super()._validate(*args, _instantiation_metadata=_instantiation_metadata) + + +class IntSchema(IntBase, NumberSchema): + + @classmethod + def _from_openapi_data(cls, arg: int, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, arg: typing.Union[Decimal, int], **kwargs: typing.Union[InstantiationMetadata]): + return super().__new__(cls, arg, **kwargs) + + +class Int32Schema( + _SchemaValidator( + inclusive_minimum=Decimal(-2147483648), + inclusive_maximum=Decimal(2147483647) + ), + IntSchema +): + pass + +class Int64Schema( + _SchemaValidator( + inclusive_minimum=Decimal(-9223372036854775808), + inclusive_maximum=Decimal(9223372036854775807) + ), + IntSchema +): + pass + + +class Float32Schema( + _SchemaValidator( + inclusive_minimum=Decimal(-3.4028234663852886e+38), + inclusive_maximum=Decimal(3.4028234663852886e+38) + ), + NumberSchema +): + + @classmethod + def _from_openapi_data(cls, arg: typing.Union[float, Decimal], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + # todo check format + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + +class Float64Schema( + _SchemaValidator( + inclusive_minimum=Decimal(-1.7976931348623157E+308), + inclusive_maximum=Decimal(1.7976931348623157E+308) + ), + NumberSchema +): + + @classmethod + def _from_openapi_data(cls, arg: typing.Union[float, Decimal], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + # todo check format + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + +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], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None) -> 'StrSchema': + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, arg: typing.Union[str, date, datetime], **kwargs: typing.Union[InstantiationMetadata]): + return super().__new__(cls, arg, **kwargs) + + +class DateSchema(DateBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, datetime], **kwargs: typing.Union[InstantiationMetadata]): + return super().__new__(cls, arg, **kwargs) + + +class DateTimeSchema(DateTimeBase, StrSchema): + + def __new__(cls, arg: typing.Union[str, datetime], **kwargs: typing.Union[InstantiationMetadata]): + 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[InstantiationMetadata]): + 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[InstantiationMetadata]): + 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': [ + ], + } + + def __new__(cls, arg: typing.Union[io.FileIO, io.BufferedReader, bytes], **kwargs: typing.Union[InstantiationMetadata]): + return super().__new__(cls, arg) + + +class BoolSchema( + _SchemaTypeChecker(typing.Union[bool]), + BoolBase, + Schema +): + + @classmethod + def _from_openapi_data(cls, arg: bool, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, arg: bool, **kwargs: typing.Union[InstantiationMetadata]): + return super().__new__(cls, arg, **kwargs) + + +class AnyTypeSchema( + _SchemaTypeChecker( + typing.Union[frozendict, tuple, Decimal, str, bool, none_type, 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], _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + return super()._from_openapi_data(arg, _instantiation_metadata=_instantiation_metadata) + + def __new__(cls, *args: typing.Union[dict, frozendict], **kwargs: typing.Union[dict, frozendict, list, tuple, Decimal, float, int, str, date, datetime, bool, None, bytes, Schema, Unset, InstantiationMetadata]): + return super().__new__(cls, *args, **kwargs) + + +schema_descendents = 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/petstore_api/signing.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/signing.py new file mode 100644 index 000000000000..22b3bf2bf1d4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/signing.py @@ -0,0 +1,416 @@ +# coding: utf-8 +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use 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 base64 import b64encode +from Crypto.IO import PEM, PKCS8 +from Crypto.Hash import SHA256, SHA512 +from Crypto.PublicKey import RSA, ECC +from Crypto.Signature import PKCS1_v1_5, pss, DSS +from email.utils import formatdate +import json +import os +import re +from time import time +from urllib.parse import urlencode, urlparse + +# The constants below define a subset of HTTP headers that can be included in the +# HTTP signature scheme. Additional headers may be included in the signature. + +# The '(request-target)' header is a calculated field that includes the HTTP verb, +# the URL path and the URL query. +HEADER_REQUEST_TARGET = '(request-target)' +# The time when the HTTP signature was generated. +HEADER_CREATED = '(created)' +# The time when the HTTP signature expires. The API server should reject HTTP requests +# that have expired. +HEADER_EXPIRES = '(expires)' +# The 'Host' header. +HEADER_HOST = 'Host' +# The 'Date' header. +HEADER_DATE = 'Date' +# When the 'Digest' header is included in the HTTP signature, the client automatically +# computes the digest of the HTTP request body, per RFC 3230. +HEADER_DIGEST = 'Digest' +# The 'Authorization' header is automatically generated by the client. It includes +# the list of signed headers and a base64-encoded signature. +HEADER_AUTHORIZATION = 'Authorization' + +# The constants below define the cryptographic schemes for the HTTP signature scheme. +SCHEME_HS2019 = 'hs2019' +SCHEME_RSA_SHA256 = 'rsa-sha256' +SCHEME_RSA_SHA512 = 'rsa-sha512' + +# The constants below define the signature algorithms that can be used for the HTTP +# signature scheme. +ALGORITHM_RSASSA_PSS = 'RSASSA-PSS' +ALGORITHM_RSASSA_PKCS1v15 = 'RSASSA-PKCS1-v1_5' + +ALGORITHM_ECDSA_MODE_FIPS_186_3 = 'fips-186-3' +ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979 = 'deterministic-rfc6979' +ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS = { + ALGORITHM_ECDSA_MODE_FIPS_186_3, + ALGORITHM_ECDSA_MODE_DETERMINISTIC_RFC6979 +} + +# The cryptographic hash algorithm for the message signature. +HASH_SHA256 = 'sha256' +HASH_SHA512 = 'sha512' + + +class HttpSigningConfiguration(object): + """The configuration parameters for the HTTP signature security scheme. + The HTTP signature security scheme is used to sign HTTP requests with a private key + which is in possession of the API client. + An 'Authorization' header is calculated by creating a hash of select headers, + and optionally the body of the HTTP request, then signing the hash value using + a private key. The 'Authorization' header is added to outbound HTTP requests. + + NOTE: This class is auto generated by OpenAPI Generator + + Ref: https://openapi-generator.tech + Do not edit the class manually. + + :param key_id: A string value specifying the identifier of the cryptographic key, + when signing HTTP requests. + :param signing_scheme: A string value specifying the signature scheme, when + signing HTTP requests. + Supported value are hs2019, rsa-sha256, rsa-sha512. + Avoid using rsa-sha256, rsa-sha512 as they are deprecated. These values are + available for server-side applications that only support the older + HTTP signature algorithms. + :param private_key_path: A string value specifying the path of the file containing + a private key. The private key is used to sign HTTP requests. + :param private_key_passphrase: A string value specifying the passphrase to decrypt + the private key. + :param signed_headers: A list of strings. Each value is the name of a HTTP header + that must be included in the HTTP signature calculation. + The two special signature headers '(request-target)' and '(created)' SHOULD be + included in SignedHeaders. + The '(created)' header expresses when the signature was created. + The '(request-target)' header is a concatenation of the lowercased :method, an + ASCII space, and the :path pseudo-headers. + When signed_headers is not specified, the client defaults to a single value, + '(created)', in the list of HTTP headers. + When SignedHeaders contains the 'Digest' value, the client performs the + following operations: + 1. Calculate a digest of request body, as specified in RFC3230, section 4.3.2. + 2. Set the 'Digest' header in the request body. + 3. Include the 'Digest' header and value in the HTTP signature. + :param signing_algorithm: A string value specifying the signature algorithm, when + signing HTTP requests. + Supported values are: + 1. For RSA keys: RSASSA-PSS, RSASSA-PKCS1-v1_5. + 2. For ECDSA keys: fips-186-3, deterministic-rfc6979. + If None, the signing algorithm is inferred from the private key. + The default signing algorithm for RSA keys is RSASSA-PSS. + The default signing algorithm for ECDSA keys is fips-186-3. + :param hash_algorithm: The hash algorithm for the signature. Supported values are + sha256 and sha512. + If the signing_scheme is rsa-sha256, the hash algorithm must be set + to None or sha256. + If the signing_scheme is rsa-sha512, the hash algorithm must be set + to None or sha512. + :param signature_max_validity: The signature max validity, expressed as + a datetime.timedelta value. It must be a positive value. + """ + def __init__(self, key_id, signing_scheme, private_key_path, + private_key_passphrase=None, + signed_headers=None, + signing_algorithm=None, + hash_algorithm=None, + signature_max_validity=None): + self.key_id = key_id + if signing_scheme not in {SCHEME_HS2019, SCHEME_RSA_SHA256, SCHEME_RSA_SHA512}: + raise Exception("Unsupported security scheme: {0}".format(signing_scheme)) + self.signing_scheme = signing_scheme + if not os.path.exists(private_key_path): + raise Exception("Private key file does not exist") + self.private_key_path = private_key_path + self.private_key_passphrase = private_key_passphrase + self.signing_algorithm = signing_algorithm + self.hash_algorithm = hash_algorithm + if signing_scheme == SCHEME_RSA_SHA256: + if self.hash_algorithm is None: + self.hash_algorithm = HASH_SHA256 + elif self.hash_algorithm != HASH_SHA256: + raise Exception("Hash algorithm must be sha256 when security scheme is %s" % + SCHEME_RSA_SHA256) + elif signing_scheme == SCHEME_RSA_SHA512: + if self.hash_algorithm is None: + self.hash_algorithm = HASH_SHA512 + elif self.hash_algorithm != HASH_SHA512: + raise Exception("Hash algorithm must be sha512 when security scheme is %s" % + SCHEME_RSA_SHA512) + elif signing_scheme == SCHEME_HS2019: + if self.hash_algorithm is None: + self.hash_algorithm = HASH_SHA256 + elif self.hash_algorithm not in {HASH_SHA256, HASH_SHA512}: + raise Exception("Invalid hash algorithm") + if signature_max_validity is not None and signature_max_validity.total_seconds() < 0: + raise Exception("The signature max validity must be a positive value") + self.signature_max_validity = signature_max_validity + # If the user has not provided any signed_headers, the default must be set to '(created)', + # as specified in the 'HTTP signature' standard. + if signed_headers is None or len(signed_headers) == 0: + signed_headers = [HEADER_CREATED] + if self.signature_max_validity is None and HEADER_EXPIRES in signed_headers: + raise Exception( + "Signature max validity must be set when " + "'(expires)' signature parameter is specified") + if len(signed_headers) != len(set(signed_headers)): + raise Exception("Cannot have duplicates in the signed_headers parameter") + if HEADER_AUTHORIZATION in signed_headers: + raise Exception("'Authorization' header cannot be included in signed headers") + self.signed_headers = signed_headers + self.private_key = None + """The private key used to sign HTTP requests. + Initialized when the PEM-encoded private key is loaded from a file. + """ + self.host = None + """The host name, optionally followed by a colon and TCP port number. + """ + self._load_private_key() + + def get_http_signature_headers(self, resource_path, method, headers, body, query_params): + """Create a cryptographic message signature for the HTTP request and add the signed headers. + + :param resource_path : A string representation of the HTTP request resource path. + :param method: A string representation of the HTTP request method, e.g. GET, POST. + :param headers: A dict containing the HTTP request headers. + :param body: The object representing the HTTP request body. + :param query_params: A string representing the HTTP request query parameters. + :return: A dict of HTTP headers that must be added to the outbound HTTP request. + """ + if method is None: + raise Exception("HTTP method must be set") + if resource_path is None: + raise Exception("Resource path must be set") + + signed_headers_list, request_headers_dict = self._get_signed_header_info( + resource_path, method, headers, body, query_params) + + header_items = [ + "{0}: {1}".format(key.lower(), value) for key, value in signed_headers_list] + string_to_sign = "\n".join(header_items) + + digest, digest_prefix = self._get_message_digest(string_to_sign.encode()) + b64_signed_msg = self._sign_digest(digest) + + request_headers_dict[HEADER_AUTHORIZATION] = self._get_authorization_header( + signed_headers_list, b64_signed_msg) + + return request_headers_dict + + def get_public_key(self): + """Returns the public key object associated with the private key. + """ + pubkey = None + if isinstance(self.private_key, RSA.RsaKey): + pubkey = self.private_key.publickey() + elif isinstance(self.private_key, ECC.EccKey): + pubkey = self.private_key.public_key() + return pubkey + + def _load_private_key(self): + """Load the private key used to sign HTTP requests. + The private key is used to sign HTTP requests as defined in + https://datatracker.ietf.org/doc/draft-cavage-http-signatures/. + """ + if self.private_key is not None: + return + with open(self.private_key_path, 'r') as f: + pem_data = f.read() + # Verify PEM Pre-Encapsulation Boundary + r = re.compile(r"\s*-----BEGIN (.*)-----\s+") + m = r.match(pem_data) + if not m: + raise ValueError("Not a valid PEM pre boundary") + pem_header = m.group(1) + if pem_header == 'RSA PRIVATE KEY': + self.private_key = RSA.importKey(pem_data, self.private_key_passphrase) + elif pem_header == 'EC PRIVATE KEY': + self.private_key = ECC.import_key(pem_data, self.private_key_passphrase) + elif pem_header in {'PRIVATE KEY', 'ENCRYPTED PRIVATE KEY'}: + # Key is in PKCS8 format, which is capable of holding many different + # types of private keys, not just EC keys. + (key_binary, pem_header, is_encrypted) = \ + PEM.decode(pem_data, self.private_key_passphrase) + (oid, privkey, params) = \ + PKCS8.unwrap(key_binary, passphrase=self.private_key_passphrase) + if oid == '1.2.840.10045.2.1': + self.private_key = ECC.import_key(pem_data, self.private_key_passphrase) + else: + raise Exception("Unsupported key: {0}. OID: {1}".format(pem_header, oid)) + else: + raise Exception("Unsupported key: {0}".format(pem_header)) + # Validate the specified signature algorithm is compatible with the private key. + if self.signing_algorithm is not None: + supported_algs = None + if isinstance(self.private_key, RSA.RsaKey): + supported_algs = {ALGORITHM_RSASSA_PSS, ALGORITHM_RSASSA_PKCS1v15} + elif isinstance(self.private_key, ECC.EccKey): + supported_algs = ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS + if supported_algs is not None and self.signing_algorithm not in supported_algs: + raise Exception( + "Signing algorithm {0} is not compatible with private key".format( + self.signing_algorithm)) + + def _get_signed_header_info(self, resource_path, method, headers, body, query_params): + """Build the HTTP headers (name, value) that need to be included in + the HTTP signature scheme. + + :param resource_path : A string representation of the HTTP request resource path. + :param method: A string representation of the HTTP request method, e.g. GET, POST. + :param headers: A dict containing the HTTP request headers. + :param body: The object (e.g. a dict) representing the HTTP request body. + :param query_params: A string representing the HTTP request query parameters. + :return: A tuple containing two dict objects: + The first dict contains the HTTP headers that are used to calculate + the HTTP signature. + The second dict contains the HTTP headers that must be added to + the outbound HTTP request. + """ + + if body is None: + body = '' + else: + body = json.dumps(body) + + # Build the '(request-target)' HTTP signature parameter. + target_host = urlparse(self.host).netloc + target_path = urlparse(self.host).path + request_target = method.lower() + " " + target_path + resource_path + if query_params: + request_target += "?" + urlencode(query_params) + + # Get UNIX time, e.g. seconds since epoch, not including leap seconds. + now = time() + # Format date per RFC 7231 section-7.1.1.2. An example is: + # Date: Wed, 21 Oct 2015 07:28:00 GMT + cdate = formatdate(timeval=now, localtime=False, usegmt=True) + # The '(created)' value MUST be a Unix timestamp integer value. + # Subsecond precision is not supported. + created = int(now) + if self.signature_max_validity is not None: + expires = now + self.signature_max_validity.total_seconds() + + signed_headers_list = [] + request_headers_dict = {} + for hdr_key in self.signed_headers: + hdr_key = hdr_key.lower() + if hdr_key == HEADER_REQUEST_TARGET: + value = request_target + elif hdr_key == HEADER_CREATED: + value = '{0}'.format(created) + elif hdr_key == HEADER_EXPIRES: + value = '{0}'.format(expires) + elif hdr_key == HEADER_DATE.lower(): + value = cdate + request_headers_dict[HEADER_DATE] = '{0}'.format(cdate) + elif hdr_key == HEADER_DIGEST.lower(): + request_body = body.encode() + body_digest, digest_prefix = self._get_message_digest(request_body) + b64_body_digest = b64encode(body_digest.digest()) + value = digest_prefix + b64_body_digest.decode('ascii') + request_headers_dict[HEADER_DIGEST] = '{0}{1}'.format( + digest_prefix, b64_body_digest.decode('ascii')) + elif hdr_key == HEADER_HOST.lower(): + value = target_host + request_headers_dict[HEADER_HOST] = '{0}'.format(target_host) + else: + value = next((v for k, v in headers.items() if k.lower() == hdr_key), None) + if value is None: + raise Exception( + "Cannot sign HTTP request. " + "Request does not contain the '{0}' header".format(hdr_key)) + signed_headers_list.append((hdr_key, value)) + + return signed_headers_list, request_headers_dict + + def _get_message_digest(self, data): + """Calculates and returns a cryptographic digest of a specified HTTP request. + + :param data: The string representation of the date to be hashed with a cryptographic hash. + :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 + to generate the 'Digest' header as specified in RFC 3230. + """ + if self.hash_algorithm == HASH_SHA512: + digest = SHA512.new() + prefix = 'SHA-512=' + elif self.hash_algorithm == HASH_SHA256: + digest = SHA256.new() + prefix = 'SHA-256=' + else: + raise Exception("Unsupported hash algorithm: {0}".format(self.hash_algorithm)) + digest.update(data) + return digest, prefix + + def _sign_digest(self, digest): + """Signs a message digest with a private key specified in the signing_info. + + :param digest: A hashing object that contains the cryptographic digest of the HTTP request. + :return: A base-64 string representing the cryptographic signature of the input digest. + """ + sig_alg = self.signing_algorithm + if isinstance(self.private_key, RSA.RsaKey): + if sig_alg is None or sig_alg == ALGORITHM_RSASSA_PSS: + # RSASSA-PSS in Section 8.1 of RFC8017. + signature = pss.new(self.private_key).sign(digest) + elif sig_alg == ALGORITHM_RSASSA_PKCS1v15: + # RSASSA-PKCS1-v1_5 in Section 8.2 of RFC8017. + signature = PKCS1_v1_5.new(self.private_key).sign(digest) + else: + raise Exception("Unsupported signature algorithm: {0}".format(sig_alg)) + elif isinstance(self.private_key, ECC.EccKey): + if sig_alg is None: + sig_alg = ALGORITHM_ECDSA_MODE_FIPS_186_3 + if sig_alg in ALGORITHM_ECDSA_KEY_SIGNING_ALGORITHMS: + # draft-ietf-httpbis-message-signatures-00 does not specify the ECDSA encoding. + # Issue: https://github.com/w3c-ccg/http-signatures/issues/107 + signature = DSS.new(key=self.private_key, mode=sig_alg, + encoding='der').sign(digest) + else: + raise Exception("Unsupported signature algorithm: {0}".format(sig_alg)) + else: + raise Exception("Unsupported private key: {0}".format(type(self.private_key))) + return b64encode(signature) + + def _get_authorization_header(self, signed_headers, signed_msg): + """Calculates and returns the value of the 'Authorization' header when signing HTTP requests. + + :param signed_headers : A list of tuples. Each value is the name of a HTTP header that + must be included in the HTTP signature calculation. + :param signed_msg: A base-64 encoded string representation of the signature. + :return: The string value of the 'Authorization' header, representing the signature + of the HTTP request. + """ + created_ts = None + expires_ts = None + for k, v in signed_headers: + if k == HEADER_CREATED: + created_ts = v + elif k == HEADER_EXPIRES: + expires_ts = v + lower_keys = [k.lower() for k, v in signed_headers] + headers_value = " ".join(lower_keys) + + auth_str = "Signature keyId=\"{0}\",algorithm=\"{1}\",".format( + self.key_id, self.signing_scheme) + if created_ts is not None: + auth_str = auth_str + "created={0},".format(created_ts) + if expires_ts is not None: + auth_str = auth_str + "expires={0},".format(expires_ts) + auth_str = auth_str + "headers=\"{0}\",signature=\"{1}\"".format( + headers_value, signed_msg.decode('ascii')) + + return auth_str diff --git a/samples/openapi3/client/petstore/python-experimental/requirements.txt b/samples/openapi3/client/petstore/python-experimental/requirements.txt new file mode 100644 index 000000000000..c9227e58a1be --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/requirements.txt @@ -0,0 +1,5 @@ +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.cfg b/samples/openapi3/client/petstore/python-experimental/setup.cfg new file mode 100644 index 000000000000..11433ee875ab --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/setup.cfg @@ -0,0 +1,2 @@ +[flake8] +max-line-length=99 diff --git a/samples/openapi3/client/petstore/python-experimental/setup.py b/samples/openapi3/client/petstore/python-experimental/setup.py new file mode 100644 index 000000000000..c0194e516366 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/setup.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 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 new file mode 100644 index 000000000000..36d9b4fa7a8c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test-requirements.txt @@ -0,0 +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-experimental/test/__init__.py b/samples/openapi3/client/petstore/python-experimental/test/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 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 new file mode 100644 index 000000000000..442b5ed138a1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_additional_properties_class.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..076df41d63fc --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_additional_properties_with_array_of_enums.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..78d674007487 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_address.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..572450a9704b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_animal.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..3ee8615f57c8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_animal_farm.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..c58dfa6202bc --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_another_fake_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 +""" + + +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_api_response.py b/samples/openapi3/client/petstore/python-experimental/test/test_api_response.py new file mode 100644 index 000000000000..63dc0ede9b2b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_api_response.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..e8abc62ef046 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_apple.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..38edc7a55daf --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_apple_req.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..cee2263dd67c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_array_holding_any_type.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..ebf1ad383672 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_array_of_array_of_number_only.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..44a59bb5263f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_array_of_enums.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..21bffad3329d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_array_of_number_only.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..4528c568690b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_array_test.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..95a19cba751e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_array_with_validations_in_items.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..77b1b2aaf304 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_banana.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..2bfbb9edb4c3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_banana_req.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..3d9429384675 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_bar.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..4af8d8947cab --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_basque_pig.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..c2e2faab188a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_boolean.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..2d73bc707f55 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_boolean_enum.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 +""" + + +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 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 new file mode 100644 index 000000000000..8cb68360735a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_capitalization.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..7c2b75fe8af8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_cat.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 +""" + + +import sys +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_cat_all_of.py b/samples/openapi3/client/petstore/python-experimental/test/test_cat_all_of.py new file mode 100644 index 000000000000..84ebd083410a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_cat_all_of.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 +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.cat_all_of import CatAllOf + + +class TestCatAllOf(unittest.TestCase): + """CatAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_CatAllOf(self): + """Test CatAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = CatAllOf() # 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 new file mode 100644 index 000000000000..8f19639fb516 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_category.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..f4be6a52a8d4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_child_cat.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 +""" + + +import sys +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_child_cat_all_of.py b/samples/openapi3/client/petstore/python-experimental/test/test_child_cat_all_of.py new file mode 100644 index 000000000000..410ac2772ab7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_child_cat_all_of.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 +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.child_cat_all_of import ChildCatAllOf + + +class TestChildCatAllOf(unittest.TestCase): + """ChildCatAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_ChildCatAllOf(self): + """Test ChildCatAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = ChildCatAllOf() # 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 new file mode 100644 index 000000000000..6a472da41aeb --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_class_model.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..70a26741f40f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_client.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..95c686785215 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_complex_quadrilateral.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 +""" + + +import sys +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_complex_quadrilateral_all_of.py b/samples/openapi3/client/petstore/python-experimental/test/test_complex_quadrilateral_all_of.py new file mode 100644 index 000000000000..96fdc5103f31 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_complex_quadrilateral_all_of.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 +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.complex_quadrilateral_all_of import ComplexQuadrilateralAllOf + + +class TestComplexQuadrilateralAllOf(unittest.TestCase): + """ComplexQuadrilateralAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_ComplexQuadrilateralAllOf(self): + """Test ComplexQuadrilateralAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = ComplexQuadrilateralAllOf() # 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 new file mode 100644 index 000000000000..92263d139452 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_composed_any_of_different_types_no_validations.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..3e48ed79fe5a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_composed_array.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..790edcc16d39 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_composed_bool.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..65c7dd5adb91 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_composed_none.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..66fdc3c591e0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_composed_number.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..6212b89f9bc1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_composed_object.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..b15712de301e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_composed_one_of_different_types.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..2bfcf2f74d36 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_composed_string.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 +""" + + +import sys +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_danish_pig.py b/samples/openapi3/client/petstore/python-experimental/test/test_danish_pig.py new file mode 100644 index 000000000000..1a46253ed9f5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_danish_pig.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..275b74c92a25 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_date_time_test.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..0edf5c5e85be --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_date_time_with_validations.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..866e5529225b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_date_with_validations.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 +""" + + +import sys +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_default_api.py b/samples/openapi3/client/petstore/python-experimental/test/test_default_api.py new file mode 100644 index 000000000000..caf174d6d4ba --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_default_api.py @@ -0,0 +1,36 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for 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 new file mode 100644 index 000000000000..4643c7af8353 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_dog.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 +""" + + +import sys +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_dog_all_of.py b/samples/openapi3/client/petstore/python-experimental/test/test_dog_all_of.py new file mode 100644 index 000000000000..89526f7051f0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_dog_all_of.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 +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.dog_all_of import DogAllOf + + +class TestDogAllOf(unittest.TestCase): + """DogAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_DogAllOf(self): + """Test DogAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = DogAllOf() # 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 new file mode 100644 index 000000000000..091d89c80e15 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_drawing.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..0b7e553a7d16 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_enum_arrays.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..298c740defab --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_enum_class.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..2022b10d5d56 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_enum_test.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..d85647271ce1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_equilateral_triangle.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 +""" + + +import sys +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_equilateral_triangle_all_of.py b/samples/openapi3/client/petstore/python-experimental/test/test_equilateral_triangle_all_of.py new file mode 100644 index 000000000000..9651e4efd43f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_equilateral_triangle_all_of.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 +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.equilateral_triangle_all_of import EquilateralTriangleAllOf + + +class TestEquilateralTriangleAllOf(unittest.TestCase): + """EquilateralTriangleAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_EquilateralTriangleAllOf(self): + """Test EquilateralTriangleAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = EquilateralTriangleAllOf() # 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 new file mode 100644 index 000000000000..abe26cc6c4da --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_fake_api.py @@ -0,0 +1,192 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for 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_json_form_data(self): + """Test case for json_form_data + + test json serialization of form data # 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_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_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_tags_123_api.py b/samples/openapi3/client/petstore/python-experimental/test/test_fake_classname_tags_123_api.py new file mode 100644 index 000000000000..b7724aaed7d1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_fake_classname_tags_123_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 +""" + + +import unittest + +import petstore_api +from petstore_api.api.fake_classname_tags_123_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_test_classname(self): + """Test case for test_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 new file mode 100644 index 000000000000..7154338bc7a5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_file.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..0b56063d59f6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_file_schema_test_class.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..69fbc69ba9e5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_foo.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..e5d081ceaa48 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_format_test.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..43a58a870c30 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_fruit.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..3745b38f17ea --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_fruit_req.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..487e5275516e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_gm_fruit.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..8820ad5f253f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_grandparent_animal.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..0019338c2bc7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_has_only_read_only.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..e654924727bc --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_health_check_result.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 +""" + + +import sys +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_inline_response_default.py b/samples/openapi3/client/petstore/python-experimental/test/test_inline_response_default.py new file mode 100644 index 000000000000..98b9b31821a7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_inline_response_default.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 +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.inline_response_default import InlineResponseDefault + + +class TestInlineResponseDefault(unittest.TestCase): + """InlineResponseDefault unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_InlineResponseDefault(self): + """Test InlineResponseDefault""" + # FIXME: construct object with mandatory attributes with example values + # model = InlineResponseDefault() # 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 new file mode 100644 index 000000000000..b94fef7543a3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..61052164aee9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum_big.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..9c94769ef704 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum_one_value.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 +""" + + +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 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 new file mode 100644 index 000000000000..bcdd005b2fb5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_integer_enum_with_default_value.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..9a982a0cb284 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_integer_max10.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..b54a5c3e1a1f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_integer_min15.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..00a236f55444 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_isosceles_triangle.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 +""" + + +import sys +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_isosceles_triangle_all_of.py b/samples/openapi3/client/petstore/python-experimental/test/test_isosceles_triangle_all_of.py new file mode 100644 index 000000000000..ec2e16403f70 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_isosceles_triangle_all_of.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 +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.isosceles_triangle_all_of import IsoscelesTriangleAllOf + + +class TestIsoscelesTriangleAllOf(unittest.TestCase): + """IsoscelesTriangleAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_IsoscelesTriangleAllOf(self): + """Test IsoscelesTriangleAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = IsoscelesTriangleAllOf() # 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 new file mode 100644 index 000000000000..361f043de97d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_mammal.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 +""" + + +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 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 new file mode 100644 index 000000000000..7239da64e296 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_map_test.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..8291a671896f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_mixed_properties_and_additional_properties_class.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..11caf2a0c0b5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_model200_response.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..61841ab2acb6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_model_return.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 +""" + + +import sys +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_name.py b/samples/openapi3/client/petstore/python-experimental/test/test_name.py new file mode 100644 index 000000000000..67b92d6ef0d3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_name.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..a76654032454 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_no_additional_properties.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 +""" + + +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 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 new file mode 100644 index 000000000000..8eeb087512f4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_nullable_class.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..7126a23ed427 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_nullable_shape.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..fac8c8653bf2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_nullable_string.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..9dff8542047a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_number.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..a1572ab7f9e5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_number_only.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..919d7c0d5a64 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_number_with_validations.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 +""" + + +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 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 new file mode 100644 index 000000000000..42994360b373 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_object_interface.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..6c8aaa4c9cf9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_object_model_with_ref_props.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 +""" + + +import sys +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_difficultly_named_props.py b/samples/openapi3/client/petstore/python-experimental/test/test_object_with_difficultly_named_props.py new file mode 100644 index 000000000000..6bd3ec317cd4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_object_with_difficultly_named_props.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 +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""" + kwargs = { + '$special[property.name]': 1, + '123-list': '', + '123Number': 2, + } + model = ObjectWithDifficultlyNamedProps(**kwargs) + self.assertEqual(model['$special[property.name]'], 1) + self.assertEqual(model['123-list'], '') + self.assertEqual(model['123Number'], 2) + self.assertEqual(model, kwargs) + + # without the required argument, an exception is raised + optional_kwargs = { + '$special[property.name]': 1, + '123Number': 2, + } + with self.assertRaisesRegex( + petstore_api.ApiTypeError, + r"ObjectWithDifficultlyNamedProps is missing 1 required argument: ['123-list']" + ): + ObjectWithDifficultlyNamedProps(**optional_kwargs) + + +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 new file mode 100644 index 000000000000..cfe0400fcee9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_object_with_validations.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..9463845b34a2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_order.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..d1507e114f0c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_parent_pet.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..dc34ae0012b9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_pet.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..d545f497297a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_pet_api.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 +""" + + +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(self): + """Test case for upload_file + + uploads an image # 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 + + +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 new file mode 100644 index 000000000000..8c092a8465b1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_pig.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..ba15e0f576a0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_player.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..cc0c203d2eaf --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_quadrilateral.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..cec68e36cf53 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_quadrilateral_interface.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..d447437eb165 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_read_only_first.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..8df062169260 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_scalene_triangle.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 +""" + + +import sys +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_scalene_triangle_all_of.py b/samples/openapi3/client/petstore/python-experimental/test/test_scalene_triangle_all_of.py new file mode 100644 index 000000000000..f81248b1517a --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_scalene_triangle_all_of.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 +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.scalene_triangle_all_of import ScaleneTriangleAllOf + + +class TestScaleneTriangleAllOf(unittest.TestCase): + """ScaleneTriangleAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_ScaleneTriangleAllOf(self): + """Test ScaleneTriangleAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = ScaleneTriangleAllOf() # 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 new file mode 100644 index 000000000000..f34053a9bcb8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_shape.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..ee182f6298cc --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_shape_or_null.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..8a6ce429abf5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_simple_quadrilateral.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 +""" + + +import sys +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_simple_quadrilateral_all_of.py b/samples/openapi3/client/petstore/python-experimental/test/test_simple_quadrilateral_all_of.py new file mode 100644 index 000000000000..ad9d92251b40 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_simple_quadrilateral_all_of.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 +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.simple_quadrilateral_all_of import SimpleQuadrilateralAllOf + + +class TestSimpleQuadrilateralAllOf(unittest.TestCase): + """SimpleQuadrilateralAllOf unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_SimpleQuadrilateralAllOf(self): + """Test SimpleQuadrilateralAllOf""" + # FIXME: construct object with mandatory attributes with example values + # model = SimpleQuadrilateralAllOf() # 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 new file mode 100644 index 000000000000..f3b94113824d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_some_object.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..b74b45db1224 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_special_model_name.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..3680a34b42a0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_store_api.py @@ -0,0 +1,58 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for 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 new file mode 100644 index 000000000000..1c62f3606b8e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_string.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..bf39e456cf0c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_string_boolean_map.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..c63cb8cba8fe --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_string_enum.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 +""" + + +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 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 new file mode 100644 index 000000000000..87073fe5be27 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_string_enum_with_default_value.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..338768440244 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_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 +""" + + +import sys +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 new file mode 100644 index 000000000000..a0325e55679f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_tag.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..e7978b7d1bf2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_triangle.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..9e498660c0b0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_triangle_interface.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..8d6e394ecb3c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_user.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..abf57b0733da --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_user_api.py @@ -0,0 +1,86 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for 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_whale.py b/samples/openapi3/client/petstore/python-experimental/test/test_whale.py new file mode 100644 index 000000000000..16cfebae3379 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_whale.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 +""" + + +import sys +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 new file mode 100644 index 000000000000..dc53745dea55 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_zebra.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 +""" + + +import sys +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/test_python.sh b/samples/openapi3/client/petstore/python-experimental/test_python.sh new file mode 100755 index 000000000000..9728a9b53163 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test_python.sh @@ -0,0 +1,33 @@ +#!/bin/bash + +REQUIREMENTS_FILE=dev-requirements.txt +REQUIREMENTS_OUT=dev-requirements.txt.log +SETUP_OUT=*.egg-info +VENV=venv +DEACTIVE=false + +export LC_ALL=en_US.UTF-8 +export LANG=en_US.UTF-8 + +### set virtualenv +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 + +### static analysis of code +#flake8 --show-source petstore_api/ + +### deactivate virtualenv +#if [ $DEACTIVE == true ]; then +# deactivate +#fi diff --git a/samples/openapi3/client/petstore/python-experimental/testfiles/1px_pic1.png b/samples/openapi3/client/petstore/python-experimental/testfiles/1px_pic1.png new file mode 100644 index 000000000000..7d3a386a2102 Binary files /dev/null and b/samples/openapi3/client/petstore/python-experimental/testfiles/1px_pic1.png differ diff --git a/samples/openapi3/client/petstore/python-experimental/testfiles/1px_pic2.png b/samples/openapi3/client/petstore/python-experimental/testfiles/1px_pic2.png new file mode 100644 index 000000000000..7d3a386a2102 Binary files /dev/null and b/samples/openapi3/client/petstore/python-experimental/testfiles/1px_pic2.png differ diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/__init__.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 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 new file mode 100644 index 000000000000..e3443becb141 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_animal.py @@ -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 +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.cat import Cat +from petstore_api.model.cat_all_of import CatAllOf +from petstore_api.model.dog import Dog +from petstore_api.model.dog_all_of import DogAllOf +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, CatAllOf) + 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, CatAllOf) + 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, DogAllOf) + 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, DogAllOf) + 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 new file mode 100644 index 000000000000..e10f99b44bca --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_any_type_schema.py @@ -0,0 +1,273 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for 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.schemas import ( + AnyTypeSchema, + DictSchema, + ListSchema, + StrSchema, + NumberSchema, + IntSchema, + BoolSchema, + NoneSchema, + DateSchema, + DateTimeSchema, + ComposedSchema, + frozendict, + Decimal, + NoneClass, + BoolClass +) + + +class TestAnyTypeSchema(unittest.TestCase): + + def testDictSchema(self): + class Model(ComposedSchema): + + @classmethod + @property + def _composed_schemas(cls): + return { + 'allOf': [ + AnyTypeSchema, + DictSchema, + ], + 'oneOf': [ + ], + 'anyOf': [ + ], + } + + 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': [ + ], + } + + 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': [ + ], + } + + 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': [ + ], + } + + 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': [ + ], + } + + 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': [ + ], + } + + 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': [ + ], + } + + 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': [ + ], + } + + 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': [ + ], + } + + 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' + + +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-experimental/tests_manual/test_array_holding_any_type.py new file mode 100644 index 000000000000..6addb31d8fc2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_array_holding_any_type.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 +""" + + +import sys +import unittest +from datetime import date, datetime, timezone + +import petstore_api +from petstore_api.model.array_holding_any_type import ArrayHoldingAnyType +from petstore_api.schemas import NoneClass, BoolClass + + +class TestArrayHoldingAnyType(unittest.TestCase): + """ArrayHoldingAnyType unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testArrayHoldingAnyType(self): + """Test ArrayHoldingAnyType""" + + enum_values = [True, False] + for enum_value in enum_values: + inst = ArrayHoldingAnyType([enum_value]) + assert isinstance(inst, ArrayHoldingAnyType) + assert isinstance(inst, tuple) + assert isinstance(inst[0], BoolClass) + assert bool(inst[0]) is enum_value + + inst = ArrayHoldingAnyType([None]) + assert isinstance(inst, ArrayHoldingAnyType) + assert isinstance(inst, tuple) + assert isinstance(inst[0], NoneClass) + + input_to_stored_value = [ + (0, 0), + (3.14, 3.14), + (date(1970, 1, 1), '1970-01-01'), + (datetime(1970, 1, 1, 0, 0, 0), '1970-01-01T00:00:00'), + (datetime(1970, 1, 1, 0, 0, 0, tzinfo=timezone.utc), '1970-01-01T00:00:00+00:00'), + ([], ()), + ({}, {}), + ('hi', 'hi'), + ] + for input, stored_value in input_to_stored_value: + inst = ArrayHoldingAnyType([input]) + assert isinstance(inst, ArrayHoldingAnyType) + assert isinstance(inst, tuple) + assert inst[0] == stored_value + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_array_with_validations_in_items.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_array_with_validations_in_items.py new file mode 100644 index 000000000000..1d3eccb68edd --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_array_with_validations_in_items.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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.array_with_validations_in_items import ArrayWithValidationsInItems + + +class TestArrayWithValidationsInItems(unittest.TestCase): + """ArrayWithValidationsInItems unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testArrayWithValidationsInItems(self): + """Test ArrayWithValidationsInItems""" + + valid_values = [-1, 5, 7] + for valid_value in valid_values: + inst = ArrayWithValidationsInItems([valid_value]) + assert isinstance(inst, ArrayWithValidationsInItems) + assert inst == (valid_value,) + + with self.assertRaisesRegex( + petstore_api.exceptions.ApiValueError, + r"Invalid value `8`, must be a value less than or equal to `7` at \('args\[0\]', 0\)" + ): + ArrayWithValidationsInItems([8]) + + with self.assertRaisesRegex( + petstore_api.exceptions.ApiValueError, + r"Invalid value `\(Decimal\('1'\), Decimal\('2'\), Decimal\('3'\)\)`, number of items must be less than or equal to `2` at \('args\[0\]',\)" + ): + ArrayWithValidationsInItems([1, 2, 3]) + + +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 new file mode 100644 index 000000000000..b2080043ce25 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_boolean_enum.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 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 test_BooleanEnum(self): + """Test BooleanEnum""" + # FIXME: construct object with mandatory attributes with example values + model = BooleanEnum(True) + model is BooleanEnum.TRUE + 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_combine_object_schemas.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_combine_object_schemas.py new file mode 100644 index 000000000000..cdbd7b1747cf --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_combine_object_schemas.py @@ -0,0 +1,152 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 AnyTypeSchema, DictSchema, IntSchema, StrSchema, Float32Schema, DateSchema +from petstore_api.model.danish_pig import DanishPig +from petstore_api.model.basque_pig import BasquePig +from petstore_api.model.no_additional_properties import NoAdditionalProperties +from petstore_api.model.address import Address +from petstore_api.model.apple_req import AppleReq +from petstore_api.model.banana_req import BananaReq +from petstore_api.model.player import Player + +class TestCombineObjectSchemas(unittest.TestCase): + pass +# def test_invalid_combo_additional_properties_missing(self): +# regex_err = ( +# r"Cannot combine additionalProperties schemas from.+?DanishPig.+?and.+?NoAdditionalProperties.+?" +# r"in.+?Combo.+?because additionalProperties does not exist in both schemas" +# ) +# with self.assertRaisesRegex(petstore_api.ApiTypeError, regex_err): +# class Combo(DanishPig, NoAdditionalProperties): +# pass +# +# def test_invalid_combo_both_no_addprops(self): +# regex_err = ( +# r"Cannot combine schemas from.+?AppleReq.+?and.+?BananaReq.+?" +# r"in.+?Combo.+?because cultivar is missing from.+?BananaReq.+?" +# ) +# with self.assertRaisesRegex(petstore_api.ApiTypeError, regex_err): +# class Combo(AppleReq, BananaReq): +# pass +# +# def test_valid_no_addprops(self): +# class FirstSchema(DictSchema): +# +# +# class a(IntSchema): +# _validations = { +# 'inclusive_maximum': 20, +# } +# +# b = Float32Schema +# +# _additional_properties = None +# +# class SecondSchema(DictSchema): +# +# +# class a(IntSchema): +# _validations = { +# 'inclusive_minimum': 10, +# } +# +# b = Float32Schema +# +# _additional_properties = None +# +# class Combo(FirstSchema, SecondSchema): +# pass +# +# assert Combo._additional_properties is None +# self.assertEqual(Combo._property_names, ('a', 'b')) +# assert Combo.a._validations == { +# 'inclusive_maximum': 20, +# 'inclusive_minimum': 10, +# } +# assert Combo.b is Float32Schema +# +# +# def test_valid_combo_additional_properties_anytype_prim(self): +# class TwoPropsAndIntegerAddProp(DictSchema): +# a = StrSchema +# b = Float32Schema +# _additional_properties = IntSchema +# +# class OnePropAndAnyTypeAddProps(DictSchema): +# c = IntSchema +# _additional_properties = AnyTypeSchema +# +# class Combo(TwoPropsAndIntegerAddProp, OnePropAndAnyTypeAddProps): +# pass +# +# assert Combo._additional_properties is TwoPropsAndIntegerAddProp._additional_properties +# self.assertEqual(Combo._property_names, ('a', 'b', 'c')) +# assert Combo.a is TwoPropsAndIntegerAddProp.a +# assert Combo.b is TwoPropsAndIntegerAddProp.b +# assert Combo.c is OnePropAndAnyTypeAddProps.c +# +# def test_invalid_type_disagreement(self): +# class StrSchemaA(DictSchema): +# a = StrSchema +# _additional_properties = AnyTypeSchema +# +# class FloatSchemaA(DictSchema): +# a = Float32Schema +# _additional_properties = AnyTypeSchema +# +# regex_err = ( +# r"Cannot combine schemas.+?StrSchema.+?and.+?Float32Schema.+?" +# r"in.+?a.+?because their types do not intersect" +# ) +# with self.assertRaisesRegex(petstore_api.ApiTypeError, regex_err): +# class Combo(StrSchemaA, FloatSchemaA): +# pass +# +# def test_valid_combo_including_self_reference(self): +# +# class EnemyPlayerAndA(DictSchema): +# a = DateSchema +# +# class enemyPlayer(DictSchema): +# heightCm = IntSchema +# _additional_properties = AnyTypeSchema +# +# _additional_properties = AnyTypeSchema +# +# class Combo(Player, EnemyPlayerAndA): +# # we have a self reference where Player.enemyPlayer = Player +# pass +# +# """ +# For Combo +# name is from Player +# enemyPlayer is from Player + EnemyPlayerAndA +# a is from EnemyPlayerAndA +# """ +# self.assertEqual(Combo._property_names, ('a', 'enemyPlayer', 'name')) +# self.assertEqual(Combo.enemyPlayer.__bases__, (EnemyPlayerAndA.enemyPlayer, Player)) +# """ +# For Combo.enemyPlayer +# heightCm is from EnemyPlayerAndA.enemyPlayer +# name is from Player.enemyPlayer +# enemyPlayer is from Player.enemyPlayer +# """ +# self.assertEqual(Combo.enemyPlayer._property_names, ('enemyPlayer', 'heightCm', 'name')) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_combine_schemas.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_combine_schemas.py new file mode 100644 index 000000000000..c6d353f66c97 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_combine_schemas.py @@ -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 +""" + + +import sys +import unittest + +import petstore_api +from petstore_api.model.date_with_validations import DateWithValidations +from petstore_api.model.date_time_with_validations import DateTimeWithValidations +from petstore_api.model.string_with_validation import StringWithValidation +from petstore_api.model.integer_enum_one_value import IntegerEnumOneValue +from petstore_api.model.integer_enum import IntegerEnum +from petstore_api.model.integer_enum_big import IntegerEnumBig +from petstore_api.model.integer_max10 import IntegerMax10 +from petstore_api.model.integer_min15 import IntegerMin15 +from petstore_api.model.nullable_string import NullableString +from petstore_api.schemas import AnyTypeSchema, Schema, NoneSchema, StrSchema, none_type, Singleton + + +class TestCombineNonObjectSchemas(unittest.TestCase): + + def test_valid_enum_plus_prim(self): + 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_to_name only contains one key + assert set(EnumPlusPrim._enum_value_to_name) == {0} + # the value is the expected enum class + enum_value_cls = EnumPlusPrim._enum_by_value[0] + assert issubclass(enum_value_cls, EnumPlusPrim) + assert issubclass(enum_value_cls, Singleton) + assert issubclass(enum_value_cls, int) + # the enum stored in that class is expected + enum_value = enum_value_cls.POSITIVE_0 + assert isinstance(enum_value, EnumPlusPrim) + assert isinstance(enum_value, Singleton) + assert isinstance(enum_value, int) + # we can access this enum from our class + assert EnumPlusPrim.POSITIVE_0 == enum_value + + # invalid value throws an exception + with self.assertRaises(petstore_api.ApiValueError): + EnumPlusPrim(9) + + # valid value succeeds + val = EnumPlusPrim(0) + assert val == 0 + assert isinstance(val, EnumPlusPrim) + assert isinstance(val, Singleton) + assert isinstance(val, int) + + 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"} + + # _enum_by_value only contains one key + assert set(IntegerOneEnum._enum_by_value) == {0} + # the value is the expected enum class + enum_value_cls = IntegerOneEnum._enum_by_value[0] + assert issubclass(enum_value_cls, IntegerOneEnum) + assert issubclass(enum_value_cls, Singleton) + assert issubclass(enum_value_cls, int) + # the enum stored in that class is expected + enum_value = enum_value_cls.POSITIVE_0 + assert isinstance(enum_value, IntegerOneEnum) + assert isinstance(enum_value, Singleton) + assert isinstance(enum_value, int) + # we can access this enum from our class + assert IntegerOneEnum.POSITIVE_0 == enum_value + + # accessing invalid enum throws an exception + invalid_enums = ['POSITIVE_1', 'POSITIVE_2'] + for invalid_enum in invalid_enums: + with self.assertRaises(KeyError): + getattr(IntegerOneEnum, invalid_enum) + + +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 new file mode 100644 index 000000000000..7f0b29ee909d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_bool.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.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""" + valid_values = [True, False] + all_values = [None, True, False, 2, 3.14, '', {}, []] + for value in all_values: + if value not in valid_values: + with self.assertRaises(petstore_api.ApiTypeError): + model = ComposedBool(value) + continue + model = ComposedBool(value) + + +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-experimental/tests_manual/test_composed_none.py new file mode 100644 index 000000000000..a37eb26b1048 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_none.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.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""" + valid_values = [None] + all_values = [None, True, False, 2, 3.14, '', {}, []] + for value in all_values: + if value not in valid_values: + with self.assertRaises(petstore_api.ApiTypeError): + model = ComposedNone(value) + continue + model = ComposedNone(value) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_number.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_number.py new file mode 100644 index 000000000000..1cd982e3f336 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_number.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.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""" + valid_values = [2, 3.14] + all_values = [None, True, False, 2, 3.14, '', {}, []] + for value in all_values: + if value not in valid_values: + with self.assertRaises(petstore_api.ApiTypeError): + model = ComposedNumber(value) + continue + model = ComposedNumber(value) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_object.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_object.py new file mode 100644 index 000000000000..7c79c574d9b3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_object.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.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""" + valid_values = [{}] + all_values = [None, True, False, 2, 3.14, '', {}, []] + for value in all_values: + if value not in valid_values: + with self.assertRaises(petstore_api.ApiTypeError): + model = ComposedObject(value) + continue + model = ComposedObject(value) + + +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 new file mode 100644 index 000000000000..f08dd500b1db --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_one_of_different_types.py @@ -0,0 +1,107 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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_composed_string.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_string.py new file mode 100644 index 000000000000..aeb5ea3a9724 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_composed_string.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.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""" + valid_values = [''] + all_values = [None, True, False, 2, 3.14, '', {}, []] + for value in all_values: + if value not in valid_values: + with self.assertRaises(petstore_api.ApiTypeError): + model = ComposedString(value) + continue + model = ComposedString(value) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_configuration.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_configuration.py new file mode 100644 index 000000000000..9218e4fc2558 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_configuration.py @@ -0,0 +1,69 @@ +# coding: utf-8 + +# flake8: noqa + +""" +Run the tests. +$ pip install nose (optional) +$ cd OpenAPIetstore-python +$ nosetests -v +""" + +import unittest + +from unittest.mock import patch +import urllib3 +from urllib3._collections import HTTPHeaderDict + +import petstore_api +from petstore_api.api_client import ApiClient +from petstore_api.api import pet_api + + +class ConfigurationTests(unittest.TestCase): + + def test_configuration(self): + config = petstore_api.Configuration() + config.host = 'http://localhost/' + + config.disabled_client_side_validations = ("multipleOf,maximum,exclusiveMaximum,minimum,exclusiveMinimum," + "maxLength,minLength,pattern,maxItems,minItems") + with self.assertRaisesRegex(ValueError, "Invalid keyword: 'foo'"): + config.disabled_client_side_validations = 'foo' + config.disabled_client_side_validations = "" + + def test_servers(self): + config = petstore_api.Configuration(server_index=1, server_variables={'version': 'v1'}) + client = pet_api.ApiClient(configuration=config) + api = pet_api.PetApi(client) + + with patch.object(ApiClient, 'request') as mock_request: + mock_request.return_value = urllib3.HTTPResponse(status=200) + api.add_pet({'name': 'pet', 'photoUrls': []}) + mock_request.assert_called_with( + 'POST', + 'http://path-server-test.petstore.local/v2/pet', + query_params=None, + headers=HTTPHeaderDict({ + 'Content-Type': 'application/json', + 'User-Agent': 'OpenAPI-Generator/1.0.0/python' + }), + fields=None, + body=b'{"name":"pet","photoUrls":[]}', + stream=False, + timeout=None, + ) + + with patch.object(ApiClient, 'request') as mock_request: + mock_request.return_value = urllib3.HTTPResponse(status=200) + api.delete_pet(path_params=dict(petId=123456789)) + mock_request.assert_called_with( + 'DELETE', + 'https://localhost:8080/v1/pet/123456789', + query_params=None, + headers={'User-Agent': 'OpenAPI-Generator/1.0.0/python'}, + fields=None, + body=None, + stream=False, + timeout=None, + ) \ No newline at end of file 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 new file mode 100644 index 000000000000..3d26e42bc1d9 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_date_time_with_validations.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 +""" + + +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"Value does not conform to the required ISO-8601 datetime format. Invalid value 'abcd' for type datetime 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 new file mode 100644 index 000000000000..fff79f16cfcd --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_date_with_validations.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for 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"Value does not conform to the required ISO-8601 date format. Invalid value 'abcd' for type date 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_deserialization.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_deserialization.py new file mode 100644 index 000000000000..f3a389d67e7b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_deserialization.py @@ -0,0 +1,458 @@ +# 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 new file mode 100644 index 000000000000..97d850d56b68 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_discard_unknown_properties.py @@ -0,0 +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 +# 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 new file mode 100644 index 000000000000..3be8388499c7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_drawing.py @@ -0,0 +1,166 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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't pass in an incorrect type for shapes + 'shapes' items has type 'Shape', which is a oneOf [Triangle, Quadrilateral] + composed schema. We are not able to assign Triangle tor Quadrilateral + to a shapes item because those instances do not include Shape validation + Shape could require additional validations that Triangle + Quadrilateral do not include + """ + from petstore_api.model.triangle import Triangle + err_msg = (r"Incorrect type passed in, required type was " + r"and passed type was at " + r"\('args\[0\]', 'shapes', 0\)") + with self.assertRaisesRegex( + petstore_api.ApiTypeError, + err_msg + ): + inst = Drawing( + mainShape=isosceles_triangle, + shapes=[ + Triangle( + shapeType="Triangle", + triangleType="EquilateralTriangle" + ) + ] + ) + + 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_extra_pool_config_options.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_extra_pool_config_options.py new file mode 100644 index 000000000000..5bf6b989ebe2 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_extra_pool_config_options.py @@ -0,0 +1,61 @@ +import unittest +from unittest.mock import patch + +import petstore_api + + +class StubPoolManager(object): + actual_kwargs = None + + def __init__(self, num_pools=10, headers=None, **kwargs): + # Matches the contract of urllib3.PoolManager + self.actual_kwargs = kwargs + + +class StubProxyManager: + actual_kwargs = None + + def __init__( + self, + proxy_url, + num_pools=10, + headers=None, + proxy_headers=None, + **kwargs + ): + # Matches the contract of urllib3.ProxyManager + self.actual_kwargs = kwargs + + +class TestExtraOptionsForPools(unittest.TestCase): + + def test_socket_options_get_passed_to_pool_manager(self): + + socket_options = ["extra", "socket", "options"] + + config = petstore_api.Configuration(host="HOST") + config.socket_options = socket_options + + with patch("petstore_api.rest.urllib3.PoolManager", StubPoolManager): + api_client = petstore_api.ApiClient(config) + + # urllib3.PoolManager promises to pass socket_options in kwargs + # to the underlying socket. So asserting that our manager + # gets it is a good start + assert api_client.rest_client.pool_manager.actual_kwargs["socket_options"] == socket_options + + def test_socket_options_get_passed_to_proxy_manager(self): + + socket_options = ["extra", "socket", "options"] + + config = petstore_api.Configuration(host="HOST") + config.socket_options = socket_options + config.proxy = True + + with patch("petstore_api.rest.urllib3.ProxyManager", StubProxyManager): + api_client = petstore_api.ApiClient(config) + + # urllib3.ProxyManager promises to pass socket_options in kwargs + # to the underlying socket. So asserting that our manager + # gets it is a good start + assert api_client.rest_client.pool_manager.actual_kwargs["socket_options"] == socket_options 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 new file mode 100644 index 000000000000..c053cee62fbc --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_fake_api.py @@ -0,0 +1,575 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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 sys +import unittest +import json +import typing +from unittest.mock import patch + +import urllib3 +from urllib3._collections import HTTPHeaderDict + +import petstore_api +from petstore_api import api_client, schemas +from petstore_api.api.fake_api import FakeApi # noqa: E501 +from petstore_api.rest import RESTClientObject + + +class TestFakeApi(unittest.TestCase): + """FakeApi unit test stubs""" + json_content_type = 'application/json' + configuration = petstore_api.Configuration() + api = FakeApi(api_client=api_client.ApiClient(configuration=configuration)) + + @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') + + @staticmethod + def __assert_request_called_with( + mock_request, + url: str, + body: typing.Optional[bytes] = None, + content_type: str = 'application/json', + fields: typing.Optional[tuple[api_client.RequestField, ...]] = None, + accept_content_type: str = 'application/json', + stream: bool = False, + ): + mock_request.assert_called_with( + 'POST', + url, + headers=HTTPHeaderDict( + { + 'Accept': accept_content_type, + 'Content-Type': content_type, + 'User-Agent': 'OpenAPI-Generator/1.0.0/python' + } + ), + body=body, + query_params=None, + fields=fields, + stream=stream, + timeout=None, + ) + + 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_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") + 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, file1]}) + 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() + + # 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) + + +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 new file mode 100644 index 000000000000..915783953177 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_format_test.py @@ -0,0 +1,134 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use 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 new file mode 100644 index 000000000000..7d31b94a8252 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_fruit.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 +""" + +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, + ], + } + ) + + """ + 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 new file mode 100644 index 000000000000..e777e603e1a1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_fruit_req.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 +""" + + +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, + ], + } + ) + + # 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 new file mode 100644 index 000000000000..6d27f7c9dab8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_gm_fruit.py @@ -0,0 +1,135 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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': [], + } + ) + + # 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 new file mode 100644 index 000000000000..9783829e30bc --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/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-experimental/tests_manual/test_integer_enum_one_value.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_integer_enum_one_value.py new file mode 100644 index 000000000000..a5d92cd0833e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_integer_enum_one_value.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 +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_json_encoder.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_json_encoder.py new file mode 100644 index 000000000000..45cce4c0f02f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_json_encoder.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 +""" + +from datetime import date +import unittest + +import petstore_api +from petstore_api import schemas +from petstore_api import api_client + + +class TestJSONEncoder(unittest.TestCase): + """Fruit unit test stubs""" + serializer = api_client.JSONEncoder() + + def test_receive_encode_str_types(self): + schema_to_value = { + schemas.StrSchema: 'hi', + schemas.DateSchema: '2021-05-09', + schemas.DateTimeSchema: '2020-01-01T00:00:00' + } + for schema, value in schema_to_value.items(): + inst = schema._from_openapi_data(value) + assert value == self.serializer.default(inst) + + def test_receive_encode_numeric_types(self): + value_to_schema = { + 1: schemas.IntSchema, + 1.0: schemas.Float32Schema, + 3.14: schemas.Float32Schema, + 4: schemas.NumberSchema, + 4.0: schemas.NumberSchema, + 7.14: schemas.NumberSchema, + } + for value, schema in value_to_schema.items(): + inst = schema._from_openapi_data(value) + pre_serialize_value = self.serializer.default(inst) + assert value == pre_serialize_value and type(value) == type(pre_serialize_value) + + +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 new file mode 100644 index 000000000000..9101280fc663 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_mammal.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 +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_no_additional_properties.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_no_additional_properties.py new file mode 100644 index 000000000000..7aff4811327f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_no_additional_properties.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 +""" + + +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 new file mode 100644 index 000000000000..2a704a708464 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_nullable_string.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 +""" + + +import sys +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 + + inst = NullableString('approved') + 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 \[NoneType, 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 new file mode 100644 index 000000000000..5cf1dfaa9c53 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_number_with_validations.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 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 new file mode 100644 index 000000000000..64a6a4c898f8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_model_with_ref_props.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 +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_difficultly_named_props.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_with_difficultly_named_props.py new file mode 100644 index 000000000000..386304ecc672 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_with_difficultly_named_props.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 +""" + + +import sys +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/tests_manual/test_object_with_validations.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_with_validations.py new file mode 100644 index 000000000000..3a443dfa39a0 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_object_with_validations.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this 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.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""" + + with self.assertRaisesRegex( + petstore_api.ApiValueError, + r"Invalid value `frozendict.frozendict\({}\)`, number of properties must be greater than or equal to `2` at \('args\[0\]',\)" + ): + ObjectWithValidations({}) + + + with self.assertRaisesRegex( + petstore_api.ApiValueError, + r"Invalid value `frozendict.frozendict\({'a': 'a'}\)`, number of properties must be greater than or equal to `2` at \('args\[0\]',\)" + ): + # number of properties less than 2 fails + model = ObjectWithValidations(a='a') + + # 2 or more properties succeeds + model = ObjectWithValidations(a='a', b='b') + model = ObjectWithValidations(a='a', b='b', c='c') + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests_manual/test_parameters.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_parameters.py new file mode 100644 index 000000000000..49940bab9026 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_parameters.py @@ -0,0 +1,954 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for 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 collections + +from petstore_api import api_client +from petstore_api import schemas + +ParamTestCase = collections.namedtuple('ParamTestCase', 'payload expected_serialization explode', defaults=[False]) + + +class TestParameter(unittest.TestCase): + in_type_to_parameter_cls = { + api_client.ParameterInType.PATH: api_client.PathParameter, + api_client.ParameterInType.QUERY: api_client.QueryParameter, + api_client.ParameterInType.COOKIE: api_client.CookieParameter, + api_client.ParameterInType.HEADER: api_client.HeaderParameter, + } + + def test_throws_exception_when_schema_and_content_omitted(self): + with self.assertRaises(ValueError): + api_client.QueryParameter( + name='' + ) + + def test_throws_exception_when_schema_and_content_input(self): + with self.assertRaises(ValueError): + schema = schemas.StrSchema + api_client.QueryParameter( + name='', + schema=schema, + content={'application/json': schema} + ) + + def test_succeeds_when_schema_or_content_input(self): + schema = schemas.StrSchema + api_client.QueryParameter( + name='', + schema=schema, + ) + api_client.QueryParameter( + name='', + content={'application/json': schema} + ) + + def test_succeeds_and_fails_for_style_and_in_type_combos(self): + style_to_in_type = { + api_client.ParameterStyle.MATRIX: {api_client.ParameterInType.PATH}, + api_client.ParameterStyle.LABEL: {api_client.ParameterInType.PATH}, + api_client.ParameterStyle.FORM: {api_client.ParameterInType.QUERY, api_client.ParameterInType.COOKIE}, + api_client.ParameterStyle.SIMPLE: {api_client.ParameterInType.PATH, api_client.ParameterInType.HEADER}, + api_client.ParameterStyle.SPACE_DELIMITED: {api_client.ParameterInType.QUERY}, + api_client.ParameterStyle.PIPE_DELIMITED: {api_client.ParameterInType.QUERY}, + api_client.ParameterStyle.DEEP_OBJECT: {api_client.ParameterInType.QUERY}, + } + schema = schemas.StrSchema + for style in style_to_in_type: + valid_in_types = style_to_in_type[style] + for valid_in_type in valid_in_types: + parameter_cls = self.in_type_to_parameter_cls[valid_in_type] + parameter_cls( + name='', + style=style, + schema=schema, + ) + invalid_in_types = {in_t for in_t in api_client.ParameterInType if in_t not in valid_in_types} + for invalid_in_type in invalid_in_types: + parameter_cls = self.in_type_to_parameter_cls[invalid_in_type] + with self.assertRaises(ValueError): + parameter_cls( + name='', + style=style, + schema=schema, + ) + + def test_throws_exception_when_invalid_name_input(self): + disallowed_names = {'Accept', 'Content-Type', 'Authorization'} + for disallowed_name in disallowed_names: + with self.assertRaises(ValueError): + api_client.HeaderParameter( + name=disallowed_name, + schema=schemas.StrSchema, + ) + + def test_query_style_form_serialization(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + () + ), + ParamTestCase( + 1, + (('color', '1'),) + ), + ParamTestCase( + 3.14, + (('color', '3.14'),) + ), + ParamTestCase( + 'blue', + (('color', 'blue'),) + ), + ParamTestCase( + 'hello world', + (('color', 'hello%20world'),) + ), + ParamTestCase( + '', + (('color', ''),) + ), + ParamTestCase( + True, + (('color', 'true'),) + ), + ParamTestCase( + False, + (('color', 'false'),) + ), + ParamTestCase( + [], + () + ), + ParamTestCase( + ['blue', 'black', 'brown'], + (('color', 'blue,black,brown'),) + ), + ParamTestCase( + ['blue', 'black', 'brown'], + ( + ('color', 'blue'), + ('color', 'black'), + ('color', 'brown'), + ), + explode=True + ), + ParamTestCase( + {}, + () + ), + ParamTestCase( + dict(R=100, G=200, B=150), + (('color', 'R,100,G,200,B,150'),) + ), + ParamTestCase( + dict(R=100, G=200, B=150), + ( + ('R', '100'), + ('G', '200'), + ('B', '150'), + ), + explode=True + ), + ) + for test_case in test_cases: + parameter = api_client.QueryParameter( + name=name, + style=api_client.ParameterStyle.FORM, + schema=schemas.AnyTypeSchema, + explode=test_case.explode, + ) + serialization = parameter.serialize(test_case.payload) + self.assertEqual(serialization, test_case.expected_serialization) + + def test_cookie_style_form_serialization(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + () + ), + ParamTestCase( + 1, + (('color', '1'),) + ), + ParamTestCase( + 3.14, + (('color', '3.14'),) + ), + ParamTestCase( + 'blue', + (('color', 'blue'),) + ), + ParamTestCase( + 'hello world', + (('color', 'hello%20world'),) + ), + ParamTestCase( + '', + (('color', ''),) + ), + ParamTestCase( + True, + (('color', 'true'),) + ), + ParamTestCase( + False, + (('color', 'false'),) + ), + ParamTestCase( + [], + () + ), + ParamTestCase( + ['blue', 'black', 'brown'], + (('color', 'blue,black,brown'),) + ), + ParamTestCase( + ['blue', 'black', 'brown'], + ( + ('color', 'blue'), + ('color', 'black'), + ('color', 'brown'), + ), + explode=True + ), + ParamTestCase( + {}, + () + ), + ParamTestCase( + dict(R=100, G=200, B=150), + (('color', 'R,100,G,200,B,150'),) + ), + ParamTestCase( + dict(R=100, G=200, B=150), + ( + ('R', '100'), + ('G', '200'), + ('B', '150'), + ), + explode=True + ), + ) + for test_case in test_cases: + parameter = api_client.CookieParameter( + name=name, + style=api_client.ParameterStyle.FORM, + schema=schemas.AnyTypeSchema, + explode=test_case.explode, + ) + serialization = parameter.serialize(test_case.payload) + self.assertEqual(serialization, test_case.expected_serialization) + + def test_style_simple_in_path_serialization(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + dict(color='') + ), + ParamTestCase( + 1, + dict(color='1') + ), + ParamTestCase( + 3.14, + dict(color='3.14') + ), + ParamTestCase( + 'blue', + dict(color='blue') + ), + ParamTestCase( + 'hello world', + dict(color='hello%20world') + ), + ParamTestCase( + '', + dict(color='') + ), + ParamTestCase( + True, + dict(color='true') + ), + ParamTestCase( + False, + dict(color='false') + ), + ParamTestCase( + [], + dict(color='') + ), + ParamTestCase( + ['blue', 'black', 'brown'], + dict(color='blue,black,brown') + ), + ParamTestCase( + ['blue', 'black', 'brown'], + dict(color='blue,black,brown'), + explode=True + ), + ParamTestCase( + {}, + dict(color='') + ), + ParamTestCase( + dict(R=100, G=200, B=150), + dict(color='R,100,G,200,B,150') + ), + ParamTestCase( + dict(R=100, G=200, B=150), + dict(color='R=100,G=200,B=150'), + explode=True + ), + ) + for test_case in test_cases: + parameter = api_client.PathParameter( + name=name, + style=api_client.ParameterStyle.SIMPLE, + schema=schemas.AnyTypeSchema, + explode=test_case.explode, + ) + serialization = parameter.serialize(test_case.payload) + self.assertEqual(serialization, test_case.expected_serialization) + + def test_style_simple_in_header_serialization(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + {} + ), + ParamTestCase( + 1, + dict(color='1') + ), + ParamTestCase( + 3.14, + dict(color='3.14') + ), + ParamTestCase( + 'blue', + dict(color='blue') + ), + ParamTestCase( + 'hello world', + dict(color='hello%20world') + ), + ParamTestCase( + '', + dict(color='') + ), + ParamTestCase( + True, + dict(color='true') + ), + ParamTestCase( + False, + dict(color='false') + ), + ParamTestCase( + [], + {} + ), + ParamTestCase( + ['blue', 'black', 'brown'], + dict(color='blue,black,brown') + ), + ParamTestCase( + ['blue', 'black', 'brown'], + dict(color='blue,black,brown'), + explode=True + ), + ParamTestCase( + {}, + {} + ), + ParamTestCase( + dict(R=100, G=200, B=150), + dict(color='R,100,G,200,B,150') + ), + ParamTestCase( + dict(R=100, G=200, B=150), + dict(color='R=100,G=200,B=150'), + explode=True + ), + ) + for test_case in test_cases: + print(test_case.payload) + parameter = api_client.HeaderParameter( + name=name, + style=api_client.ParameterStyle.SIMPLE, + schema=schemas.AnyTypeSchema, + explode=test_case.explode, + ) + serialization = parameter.serialize(test_case.payload) + self.assertEqual(serialization, test_case.expected_serialization) + + def test_style_label_in_path_serialization(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + dict(color='') + ), + ParamTestCase( + 1, + dict(color='.1') + ), + ParamTestCase( + 3.14, + dict(color='.3.14') + ), + ParamTestCase( + 'blue', + dict(color='.blue') + ), + ParamTestCase( + 'hello world', + dict(color='.hello%20world') + ), + ParamTestCase( + '', + dict(color='.') + ), + ParamTestCase( + True, + dict(color='.true') + ), + ParamTestCase( + False, + dict(color='.false') + ), + ParamTestCase( + [], + dict(color='') + ), + ParamTestCase( + ['blue', 'black', 'brown'], + dict(color='.blue.black.brown') + ), + ParamTestCase( + ['blue', 'black', 'brown'], + dict(color='.blue.black.brown'), + explode=True + ), + ParamTestCase( + {}, + dict(color='') + ), + ParamTestCase( + dict(R=100, G=200, B=150), + dict(color='.R.100.G.200.B.150') + ), + ParamTestCase( + dict(R=100, G=200, B=150), + dict(color='.R=100.G=200.B=150'), + explode=True + ), + ) + for test_case in test_cases: + parameter = api_client.PathParameter( + name=name, + style=api_client.ParameterStyle.LABEL, + schema=schemas.AnyTypeSchema, + explode=test_case.explode, + ) + serialization = parameter.serialize(test_case.payload) + self.assertEqual(serialization, test_case.expected_serialization) + + def test_style_matrix_in_path_serialization(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + dict(color='') + ), + ParamTestCase( + 1, + dict(color=';color=1') + ), + ParamTestCase( + 3.14, + dict(color=';color=3.14') + ), + ParamTestCase( + 'blue', + dict(color=';color=blue') + ), + ParamTestCase( + 'hello world', + dict(color=';color=hello%20world') + ), + ParamTestCase( + '', + dict(color=';color') + ), + ParamTestCase( + True, + dict(color=';color=true') + ), + ParamTestCase( + False, + dict(color=';color=false') + ), + ParamTestCase( + [], + dict(color='') + ), + ParamTestCase( + ['blue', 'black', 'brown'], + dict(color=';color=blue,black,brown') + ), + ParamTestCase( + ['blue', 'black', 'brown'], + dict(color=';color=blue;color=black;color=brown'), + explode=True + ), + ParamTestCase( + {}, + dict(color='') + ), + ParamTestCase( + dict(R=100, G=200, B=150), + dict(color=';color=R,100,G,200,B,150') + ), + ParamTestCase( + dict(R=100, G=200, B=150), + dict(color=';R=100;G=200;B=150'), + explode=True + ), + ) + for test_case in test_cases: + parameter = api_client.PathParameter( + name=name, + style=api_client.ParameterStyle.MATRIX, + schema=schemas.AnyTypeSchema, + explode=test_case.explode, + ) + serialization = parameter.serialize(test_case.payload) + self.assertEqual(serialization, test_case.expected_serialization) + + def test_style_space_delimited_serialization(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + () + ), + ParamTestCase( + 1, + (('color', '1'),) + ), + ParamTestCase( + 3.14, + (('color', '3.14'),) + ), + ParamTestCase( + 'blue', + (('color', 'blue'),) + ), + ParamTestCase( + 'hello world', + (('color', 'hello%20world'),) + ), + ParamTestCase( + '', + (('color', ''),) + ), + ParamTestCase( + True, + (('color', 'true'),) + ), + ParamTestCase( + False, + (('color', 'false'),) + ), + ParamTestCase( + [], + () + ), + ParamTestCase( + ['blue', 'black', 'brown'], + (('color', 'blue%20black%20brown'),) + ), + ParamTestCase( + ['blue', 'black', 'brown'], + (('color', 'color=blue%20color=black%20color=brown'),), + explode=True + ), + ParamTestCase( + {}, + () + ), + ParamTestCase( + dict(R=100, G=200, B=150), + (('color', 'R%20100%20G%20200%20B%20150'),) + ), + ParamTestCase( + dict(R=100, G=200, B=150), + (('color', 'R=100%20G=200%20B=150'),), + explode=True + ), + ) + for test_case in test_cases: + parameter = api_client.QueryParameter( + name=name, + style=api_client.ParameterStyle.SPACE_DELIMITED, + schema=schemas.AnyTypeSchema, + explode=test_case.explode, + ) + serialization = parameter.serialize(test_case.payload) + self.assertEqual(serialization, test_case.expected_serialization) + + def test_style_pipe_delimited_serialization(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + () + ), + ParamTestCase( + 1, + (('color', '1'),) + ), + ParamTestCase( + 3.14, + (('color', '3.14'),) + ), + ParamTestCase( + 'blue', + (('color', 'blue'),) + ), + ParamTestCase( + 'hello world', + (('color', 'hello%20world'),) + ), + ParamTestCase( + '', + (('color', ''),) + ), + ParamTestCase( + True, + (('color', 'true'),) + ), + ParamTestCase( + False, + (('color', 'false'),) + ), + ParamTestCase( + [], + () + ), + ParamTestCase( + ['blue', 'black', 'brown'], + (('color', 'blue|black|brown'),) + ), + ParamTestCase( + ['blue', 'black', 'brown'], + (('color', 'color=blue|color=black|color=brown'),), + explode=True + ), + ParamTestCase( + {}, + () + ), + ParamTestCase( + dict(R=100, G=200, B=150), + (('color', 'R|100|G|200|B|150'),) + ), + ParamTestCase( + dict(R=100, G=200, B=150), + (('color', 'R=100|G=200|B=150'),), + explode=True + ), + ) + for test_case in test_cases: + parameter = api_client.QueryParameter( + name=name, + style=api_client.ParameterStyle.PIPE_DELIMITED, + schema=schemas.AnyTypeSchema, + explode=test_case.explode, + ) + serialization = parameter.serialize(test_case.payload) + self.assertEqual(serialization, test_case.expected_serialization) + + def test_path_params_no_style(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + dict(color='') + ), + ParamTestCase( + 1, + dict(color='1') + ), + ParamTestCase( + 3.14, + dict(color='3.14') + ), + ParamTestCase( + 'blue', + dict(color='blue') + ), + ParamTestCase( + 'hello world', + dict(color='hello%20world') + ), + ParamTestCase( + '', + dict(color='') + ), + ParamTestCase( + True, + dict(color='true') + ), + ParamTestCase( + False, + dict(color='false') + ), + ParamTestCase( + [], + dict(color='') + ), + ParamTestCase( + ['blue', 'black', 'brown'], + dict(color='blue,black,brown') + ), + ParamTestCase( + {}, + dict(color='') + ), + ParamTestCase( + dict(R=100, G=200, B=150), + dict(color='R,100,G,200,B,150') + ), + ) + for test_case in test_cases: + parameter = api_client.PathParameter( + name=name, + schema=schemas.AnyTypeSchema, + ) + serialization = parameter.serialize(test_case.payload) + self.assertEqual(serialization, test_case.expected_serialization) + + def test_header_params_no_style(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + {} + ), + ParamTestCase( + 1, + dict(color='1') + ), + ParamTestCase( + 3.14, + dict(color='3.14') + ), + ParamTestCase( + 'blue', + dict(color='blue') + ), + ParamTestCase( + 'hello world', + dict(color='hello%20world') + ), + ParamTestCase( + '', + dict(color='') + ), + ParamTestCase( + True, + dict(color='true') + ), + ParamTestCase( + False, + dict(color='false') + ), + ParamTestCase( + [], + {} + ), + ParamTestCase( + ['blue', 'black', 'brown'], + dict(color='blue,black,brown') + ), + ParamTestCase( + {}, + {} + ), + ParamTestCase( + dict(R=100, G=200, B=150), + dict(color='R,100,G,200,B,150') + ), + ) + for test_case in test_cases: + parameter = api_client.HeaderParameter( + name=name, + schema=schemas.AnyTypeSchema, + ) + serialization = parameter.serialize(test_case.payload) + self.assertEqual(serialization, test_case.expected_serialization) + + def test_query_or_cookie_params_no_style(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + () + ), + ParamTestCase( + 1, + (('color', '1'),) + ), + ParamTestCase( + 3.14, + (('color', '3.14'),) + ), + ParamTestCase( + 'blue', + (('color', 'blue'),) + ), + ParamTestCase( + 'hello world', + (('color', 'hello%20world'),) + ), + ParamTestCase( + '', + (('color', ''),) + ), + ParamTestCase( + True, + (('color', 'true'),) + ), + ParamTestCase( + False, + (('color', 'false'),) + ), + ParamTestCase( + [], + () + ), + ParamTestCase( + ['blue', 'black', 'brown'], + (('color', 'blue,black,brown'),) + ), + ParamTestCase( + {}, + () + ), + ParamTestCase( + dict(R=100, G=200, B=150), + (('color', 'R,100,G,200,B,150'),) + ), + ) + for in_type in {api_client.ParameterInType.QUERY, api_client.ParameterInType.COOKIE}: + for test_case in test_cases: + parameter_cls = self.in_type_to_parameter_cls[in_type] + parameter = parameter_cls( + name=name, + schema=schemas.AnyTypeSchema, + ) + serialization = parameter.serialize(test_case.payload) + self.assertEqual(serialization, test_case.expected_serialization) + + def test_checks_content_lengths(self): + with self.assertRaises(ValueError): + api_client.QueryParameter( + name='', content={} + ) + with self.assertRaises(ValueError): + api_client.QueryParameter( + name='', + content={'application/json': schemas.AnyTypeSchema, 'text/plain': schemas.AnyTypeSchema} + ) + # valid length works + api_client.QueryParameter( + name='', + content={'application/json': schemas.AnyTypeSchema} + ) + + def test_content_json_serialization(self): + name = 'color' + test_cases = ( + ParamTestCase( + None, + {'color': 'null'} + ), + ParamTestCase( + 1, + {'color': '1'} + ), + ParamTestCase( + 3.14, + {'color': '3.14'} + ), + ParamTestCase( + 'blue', + {'color': '"blue"'} + ), + ParamTestCase( + 'hello world', + {'color': '"hello world"'} + ), + ParamTestCase( + '', + {'color': '""'} + ), + ParamTestCase( + True, + {'color': 'true'} + ), + ParamTestCase( + False, + {'color': 'false'} + ), + ParamTestCase( + [], + {'color': '[]'} + ), + ParamTestCase( + ['blue', 'black', 'brown'], + {'color': '["blue", "black", "brown"]'} + ), + ParamTestCase( + {}, + {'color': '{}'} + ), + ParamTestCase( + dict(R=100, G=200, B=150), + {'color': '{"R": 100, "G": 200, "B": 150}'} + ), + ) + for test_case in test_cases: + parameter = api_client.HeaderParameter( + 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( + name='color', + content={'text/plain': schemas.AnyTypeSchema} + ) + parameter.serialize(None) + + +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 new file mode 100644 index 000000000000..171310075abf --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_parent_pet.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.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 new file mode 100644 index 000000000000..dff97bc716ad --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_quadrilateral.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 +""" + + +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_request_body.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_request_body.py new file mode 100644 index 000000000000..88e9b67f6917 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_request_body.py @@ -0,0 +1,147 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + +import collections +import json +import unittest + +from petstore_api import api_client, exceptions, schemas + +ParamTestCase = collections.namedtuple('ParamTestCase', 'payload expected_serialization') + + +class TestParameter(unittest.TestCase): + + def test_throws_exception_when_content_is_invalid_size(self): + with self.assertRaises(ValueError): + api_client.RequestBody( + content={} + ) + + def test_content_json_serialization(self): + payloads = [ + None, + 1, + 3.14, + 'blue', + 'hello world', + '', + True, + False, + [], + ['blue', 'black', 'brown'], + {}, + dict(R=100, G=200, B=150), + ] + for payload in payloads: + request_body = api_client.RequestBody( + content={'application/json': api_client.MediaType(schema=schemas.AnyTypeSchema)} + ) + serialization = request_body.serialize(payload, 'application/json') + self.assertEqual( + serialization, + dict(body=json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode('utf-8')) + ) + + def test_content_multipart_form_data_serialization(self): + payload = dict( + some_null=None, + some_bool=True, + some_str='a', + some_int=1, + some_float=3.14, + some_list=[], + some_dict={}, + some_bytes=b'abc' + ) + request_body = api_client.RequestBody( + content={'multipart/form-data': api_client.MediaType(schema=schemas.AnyTypeSchema)} + ) + serialization = request_body.serialize(payload, 'multipart/form-data') + self.assertEqual( + serialization, + dict( + fields=( + api_client.RequestField( + name='some_null', data='null', headers={'Content-Type': 'application/json'}), + api_client.RequestField( + name='some_bool', data='true', headers={'Content-Type': 'application/json'}), + api_client.RequestField( + name='some_str', data='a', headers={'Content-Type': 'text/plain'}), + api_client.RequestField( + name='some_int', data='1', headers={'Content-Type': 'application/json'}), + api_client.RequestField( + name='some_float', data='3.14', headers={'Content-Type': 'application/json'}), + api_client.RequestField( + name='some_list', data='[]', headers={'Content-Type': 'application/json'}), + api_client.RequestField( + name='some_dict', data='{}', headers={'Content-Type': 'application/json'}), + api_client.RequestField( + name='some_bytes', data=b'abc', headers={'Content-Type': 'application/octet-stream'}) + ) + ) + ) + + def test_throws_error_for_nonexistant_content_type(self): + request_body = api_client.RequestBody( + content={'application/json': api_client.MediaType(schema=schemas.AnyTypeSchema)} + ) + with self.assertRaises(KeyError): + request_body.serialize(None, 'abc/def') + + def test_throws_error_for_not_implemented_content_type(self): + request_body = api_client.RequestBody( + content={ + 'application/json': api_client.MediaType(schema=schemas.AnyTypeSchema), + 'text/css': api_client.MediaType(schema=schemas.AnyTypeSchema) + } + ) + with self.assertRaises(NotImplementedError): + request_body.serialize(None, 'text/css') + + def test_application_x_www_form_urlencoded_serialization(self): + payload = dict( + some_null=None, + some_str='a', + some_int=1, + some_float=3.14, + some_list=[], + some_dict={}, + ) + content_type = 'application/x-www-form-urlencoded' + request_body = api_client.RequestBody( + content={content_type: api_client.MediaType(schema=schemas.AnyTypeSchema)} + ) + serialization = request_body.serialize(payload, content_type) + self.assertEqual( + serialization, + {'fields': (('some_str', 'a'), ('some_int', '1'), ('some_float', '3.14'))} + ) + + serialization = request_body.serialize({}, content_type) + self.assertEqual( + serialization, + {} + ) + + invalid_payloads = [ + dict(some_bool=True), + dict(some_bytes=b'abc'), + dict(some_list_with_data=[0]), + dict(some_dict_with_data={'a': 'b'}), + ] + for invalid_payload in invalid_payloads: + with self.assertRaises(exceptions.ApiValueError): + request_body.serialize(invalid_payload, content_type) + + +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 new file mode 100644 index 000000000000..ce8906fdd139 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_shape.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 +""" + + +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 new file mode 100644 index 000000000000..efba299d9f3c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_string_enum.py @@ -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 +""" + + +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): + """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) + + inst = StringEnum('approved') + assert isinstance(inst, StringEnum) + assert isinstance(inst, Singleton) + assert isinstance(inst, str) + assert inst == 'approved' + + 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 new file mode 100644 index 000000000000..286b5b0f9eb1 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_triangle.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.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_validate.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_validate.py new file mode 100644 index 000000000000..32a7f60d1caa --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/test_validate.py @@ -0,0 +1,330 @@ +# coding: utf-8 + +from collections import defaultdict +from decimal import Decimal +import sys +import typing +from unittest.mock import patch +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.dog_all_of import DogAllOf +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, + StrSchema, + NumberSchema, + Schema, + InstantiationMetadata, + Int64Schema, + StrBase, + NumberBase, + DictBase, + ListBase, + frozendict, +) + +class TestValidateResults(unittest.TestCase): + + def test_str_validate(self): + im = InstantiationMetadata() + path_to_schemas = StringWithValidation._validate('abcdefg', _instantiation_metadata=im) + assert path_to_schemas == {('args[0]',): set([StringWithValidation, str])} + + def test_number_validate(self): + im = InstantiationMetadata() + path_to_schemas = NumberWithValidations._validate(Decimal(11), _instantiation_metadata=im) + assert path_to_schemas == {('args[0]',): set([NumberWithValidations, Decimal])} + + def test_str_enum_validate(self): + im = InstantiationMetadata() + path_to_schemas = StringEnum._validate('placed', _instantiation_metadata=im) + assert path_to_schemas == {('args[0]',): set([StringEnum])} + + def test_nullable_enum_validate(self): + im = InstantiationMetadata() + path_to_schemas = StringEnum._validate(None, _instantiation_metadata=im) + assert path_to_schemas == {('args[0]',): set([StringEnum])} + + def test_empty_list_validate(self): + im = InstantiationMetadata() + path_to_schemas = ArrayHoldingAnyType._validate((), _instantiation_metadata=im) + assert path_to_schemas == {('args[0]',): set([ArrayHoldingAnyType, tuple])} + + def test_list_validate(self): + im = InstantiationMetadata() + path_to_schemas = ArrayHoldingAnyType._validate((Decimal(1), 'a'), _instantiation_metadata=im) + 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): + im = InstantiationMetadata() + path_to_schemas = Foo._validate(frozendict({}), _instantiation_metadata=im) + assert path_to_schemas == {('args[0]',): set([Foo, frozendict])} + + def test_dict_validate(self): + im = InstantiationMetadata() + path_to_schemas = Foo._validate(frozendict({'bar': 'a', 'additional': Decimal(0)}), _instantiation_metadata=im) + 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): + im = InstantiationMetadata() + path_to_schemas = Animal._validate(frozendict(className='Dog', color='black'), _instantiation_metadata=im) + assert path_to_schemas == { + ('args[0]',): set([Animal, Dog, DogAllOf, frozendict]), + ('args[0]', 'className'): set([StrSchema, AnyTypeSchema, str]), + ('args[0]', 'color'): set([StrSchema, AnyTypeSchema, str]), + } + + def test_bool_enum_validate(self): + im = InstantiationMetadata() + path_to_schemas = BooleanEnum._validate(True, _instantiation_metadata=im) + assert path_to_schemas == { + ('args[0]',): set([BooleanEnum]) + } + + def test_oneof_composition_pig_validate(self): + im = InstantiationMetadata() + path_to_schemas = Pig._validate(frozendict(className='DanishPig'), _instantiation_metadata=im) + 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): + im = InstantiationMetadata() + path_to_schemas = GmFruit._validate(frozendict(cultivar='GoldenDelicious', lengthCm=Decimal(10)), _instantiation_metadata=im) + 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: + instance = 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: + instance = 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): + expected_call_by_index = { + 0: [ + ArrayWithValidationsInItems, + ((Decimal('7'),),), + InstantiationMetadata(path_to_item=('args[0]',)) + ], + 1: [ + ArrayWithValidationsInItems._items, + (Decimal('7'),), + InstantiationMetadata(path_to_item=('args[0]', 0)) + ] + } + call_index = 0 + result_by_call_index = { + 0: defaultdict(set, [( ('args[0]',), set([ArrayWithValidationsInItems, tuple]))] ), + 1: defaultdict(set, [( ('args[0]', 0), set([ArrayWithValidationsInItems._items, Decimal]) )] ), + } + + @classmethod + def new_validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + nonlocal call_index + assert [cls, args, _instantiation_metadata] == expected_call_by_index[call_index] + result = result_by_call_index.get(call_index) + call_index += 1 + if result is None: + raise petstore_api.ApiValueError('boom') + return result + + with patch.object(Schema, '_validate', new=new_validate): + ArrayWithValidationsInItems([7]) + + def test_list_validate_direct_instantiation_cast_item(self): + # validation is skipped if items are of the correct type + expected_call_by_index = { + 0: [ + ArrayWithValidationsInItems, + ((Decimal('7'),),), + InstantiationMetadata(path_to_item=('args[0]',)) + ], + } + call_index = 0 + result_by_call_index = { + 0: defaultdict(set, [( ('args[0]',), set([ArrayWithValidationsInItems, tuple]))] ), + } + + @classmethod + def new_validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + nonlocal call_index + assert [cls, args, _instantiation_metadata] == expected_call_by_index[call_index] + result = result_by_call_index.get(call_index) + call_index += 1 + if result is None: + raise petstore_api.ApiValueError('boom') + return result + + item = ArrayWithValidationsInItems._items(7) + with patch.object(Schema, '_validate', new=new_validate): + ArrayWithValidationsInItems([item]) + + def test_list_validate_from_openai_data_instantiation(self): + expected_call_by_index = { + 0: [ + ArrayWithValidationsInItems, + ((Decimal('7'),),), + InstantiationMetadata(path_to_item=('args[0]',), from_server=True) + ], + 1: [ + ArrayWithValidationsInItems._items, + (Decimal('7'),), + InstantiationMetadata(path_to_item=('args[0]', 0), from_server=True) + ] + } + call_index = 0 + result_by_call_index = { + 0: defaultdict(set, [( ('args[0]',), set([ArrayWithValidationsInItems, tuple]))] ), + 1: defaultdict(set, [( ('args[0]', 0), set([ArrayWithValidationsInItems._items, Decimal]) )] ), + } + + @classmethod + def new_validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + nonlocal call_index + assert [cls, args, _instantiation_metadata] == expected_call_by_index[call_index] + result = result_by_call_index.get(call_index) + call_index += 1 + if result is None: + raise petstore_api.ApiValueError('boom') + return result + + with patch.object(Schema, '_validate', new=new_validate): + ArrayWithValidationsInItems._from_openapi_data([7]) + + def test_dict_validate_direct_instantiation(self): + expected_call_by_index = { + 0: [ + Foo, + (frozendict({'bar': 'a'}),), + InstantiationMetadata(path_to_item=('args[0]',)) + ], + 1: [ + StrSchema, + ('a',), + InstantiationMetadata(path_to_item=('args[0]', 'bar')) + ] + } + call_index = 0 + result_by_call_index = { + 0: defaultdict(set, [( ('args[0]',), set([Foo, frozendict]))] ), + 1: defaultdict(set, [( ('args[0]', 'bar'), set([StrSchema, str]) )] ), + } + + @classmethod + def new_validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + nonlocal call_index + assert [cls, args, _instantiation_metadata] == expected_call_by_index[call_index] + result = result_by_call_index.get(call_index) + call_index += 1 + if result is None: + raise petstore_api.ApiValueError('boom') + return result + + with patch.object(Schema, '_validate', new=new_validate): + Foo(bar='a') + + def test_dict_validate_direct_instantiation_cast_item(self): + expected_call_by_index = { + 0: [ + Foo, + (frozendict({'bar': 'a'}),), + InstantiationMetadata(path_to_item=('args[0]',)) + ], + } + call_index = 0 + result_by_call_index = { + 0: defaultdict(set, [( ('args[0]',), set([Foo, frozendict]))] ), + } + + @classmethod + def new_validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + nonlocal call_index + assert [cls, args, _instantiation_metadata] == expected_call_by_index[call_index] + result = result_by_call_index.get(call_index) + call_index += 1 + if result is None: + raise petstore_api.ApiValueError('boom') + return result + + bar = StrSchema('a') + with patch.object(Schema, '_validate', new=new_validate): + Foo(bar=bar) + + def test_dict_validate_from_openapi_data_instantiation(self): + expected_call_by_index = { + 0: [ + Foo, + (frozendict({'bar': 'a'}),), + InstantiationMetadata(path_to_item=('args[0]',), from_server=True) + ], + 1: [ + StrSchema, + ('a',), + InstantiationMetadata(path_to_item=('args[0]', 'bar'), from_server=True) + ] + } + call_index = 0 + result_by_call_index = { + 0: defaultdict(set, [( ('args[0]',), set([Foo, frozendict]))] ), + 1: defaultdict(set, [( ('args[0]', 'bar'), set([StrSchema, str]) )] ), + } + + @classmethod + def new_validate(cls, *args, _instantiation_metadata: typing.Optional[InstantiationMetadata] = None): + nonlocal call_index + assert [cls, args, _instantiation_metadata] == expected_call_by_index[call_index] + result = result_by_call_index.get(call_index) + call_index += 1 + if result is None: + raise petstore_api.ApiValueError('boom') + return result + + with patch.object(Schema, '_validate', new=new_validate): + Foo._from_openapi_data({'bar': 'a'}) + + +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 new file mode 100644 index 000000000000..88bd8ed12d44 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/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-experimental/tests_manual/util.py b/samples/openapi3/client/petstore/python-experimental/tests_manual/util.py new file mode 100644 index 000000000000..113d7dcc5478 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests_manual/util.py @@ -0,0 +1,8 @@ +# flake8: noqa + +import random + + +def id_gen(bits=32): + """ Returns a n-bit randomly generated int """ + return int(random.getrandbits(bits)) diff --git a/samples/openapi3/client/petstore/python-experimental/tox.ini b/samples/openapi3/client/petstore/python-experimental/tox.ini new file mode 100644 index 000000000000..8989fc3c4d96 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/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