diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java index 590e17f6326..7f9a77d3132 100755 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java @@ -27,15 +27,16 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig super(); eggPackage = module + "-python"; - invokerPackage = eggPackage + "/" + module; + + invokerPackage = eggPackage + File.separatorChar + module; - outputFolder = "generated-code/python"; + outputFolder = "generated-code" + File.separatorChar + "python"; modelTemplateFiles.put("model.mustache", ".py"); apiTemplateFiles.put("api.mustache", ".py"); templateDir = "python"; - apiPackage = invokerPackage + ".apis"; - modelPackage = invokerPackage + ".models"; + apiPackage = invokerPackage + File.separatorChar + "apis"; + modelPackage = invokerPackage + File.separatorChar + "models"; languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("int"); @@ -68,13 +69,12 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("README.mustache", eggPackage, "README.md")); supportingFiles.add(new SupportingFile("setup.mustache", eggPackage, "setup.py")); - supportingFiles.add(new SupportingFile("swagger.mustache", invokerPackage, "swagger.py")); + supportingFiles.add(new SupportingFile("api_client.mustache", invokerPackage, "api_client.py")); supportingFiles.add(new SupportingFile("rest.mustache", invokerPackage, "rest.py")); - supportingFiles.add(new SupportingFile("util.mustache", invokerPackage, "util.py")); - supportingFiles.add(new SupportingFile("config.mustache", invokerPackage, "config.py")); + supportingFiles.add(new SupportingFile("configuration.mustache", invokerPackage, "configuration.py")); supportingFiles.add(new SupportingFile("__init__package.mustache", invokerPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage.replace('.', File.separatorChar), "__init__.py")); - supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage.replace('.', File.separatorChar), "__init__.py")); + supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); } @Override @@ -84,11 +84,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar); } public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar); } @Override diff --git a/modules/swagger-codegen/src/main/resources/python/__init__package.mustache b/modules/swagger-codegen/src/main/resources/python/__init__package.mustache index 7b48136d3a9..921f4dac0eb 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__package.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__package.mustache @@ -7,4 +7,4 @@ from __future__ import absolute_import {{#apiInfo}}{{#apis}}from .apis.{{classVarName}} import {{classname}} {{/apis}}{{/apiInfo}} # import ApiClient -from .swagger import ApiClient +from .api_client import ApiClient diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index d5e24398f0e..7153ee2b040 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -27,9 +27,8 @@ import os # python 2 and python 3 compatibility library from six import iteritems -from ..util import remove_none - -from .. import config +from .. import configuration +from ..api_client import ApiClient {{#operations}} class {{classname}}(object): @@ -38,7 +37,10 @@ class {{classname}}(object): if api_client: self.api_client = api_client else: - self.api_client = config.api_client + if not configuration.api_client: + configuration.api_client = ApiClient('{{basePath}}') + self.api_client = configuration.api_client + {{#operation}} def {{nickname}}(self, {{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}**kwargs): """ @@ -66,13 +68,32 @@ class {{classname}}(object): resource_path = '{{path}}'.replace('{format}', 'json') method = '{{httpMethod}}' - path_params = remove_none(dict({{#pathParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/pathParams}})) - query_params = remove_none(dict({{#queryParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/queryParams}})) - header_params = remove_none(dict({{#headerParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/headerParams}})) - form_params = remove_none(dict({{#formParams}}{{^isFile}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/isFile}}{{/formParams}})) - files = remove_none(dict({{#formParams}}{{#isFile}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/isFile}}{{/formParams}})) - body_params = {{#bodyParam}}params.get('{{paramName}}'){{/bodyParam}}{{^bodyParam}}None{{/bodyParam}} - + path_params = {} + {{#pathParams}} + if '{{paramName}}' in params: + path_params['{{baseName}}'] = params['{{paramName}}'] + {{/pathParams}} + query_params = {} + {{#queryParams}} + if '{{paramName}}' in params: + query_params['{{baseName}}'] = params['{{paramName}}'] + {{/queryParams}} + header_params = {} + {{#headerParams}} + if '{{paramName}}' in params: + header_params['{{baseName}}'] = params['{{paramName}}'] + {{/headerParams}} + form_params = {} + files = {} + {{#formParams}} + if '{{paramName}}' in params: + {{#notFile}}form_params['{{baseName}}'] = params['{{paramName}}']{{/notFile}}{{#isFile}}files['{{baseName}}'] = params['{{paramName}}']{{/isFile}} + {{/formParams}} + body_params = None + {{#bodyParam}} + if '{{paramName}}' in params: + body_params = params['{{paramName}}'] + {{/bodyParam}} # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept([{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) if not header_params['Accept']: @@ -81,9 +102,12 @@ class {{classname}}(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) + # Authentication setting + auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}) + response={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, auth_settings=auth_settings) {{#returnType}} return response {{/returnType}}{{/operation}} diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py b/modules/swagger-codegen/src/main/resources/python/api_client.mustache similarity index 86% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py rename to modules/swagger-codegen/src/main/resources/python/api_client.mustache index 21430c469c8..b8cc4cc2a84 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -28,6 +28,7 @@ except ImportError: # for python2 from urllib import quote +from . import configuration class ApiClient(object): """ @@ -37,7 +38,7 @@ class ApiClient(object): :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 """ - def __init__(self, host=None, header_name=None, header_value=None): + def __init__(self, host=configuration.host, header_name=None, header_value=None): self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value @@ -58,15 +59,15 @@ class ApiClient(object): self.default_headers[header_name] = header_value def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, response=None): + body=None, post_params=None, files=None, response=None, auth_settings=None): # headers parameters - headers = self.default_headers.copy() - headers.update(header_params) + header_params = header_params or {} + header_params.update(self.default_headers) if self.cookie: - headers['Cookie'] = self.cookie - if headers: - headers = self.sanitize_for_serialization(headers) + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) # path parameters if path_params: @@ -85,6 +86,9 @@ class ApiClient(object): post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) + # auth setting + self.update_params_for_auth(header_params, query_params, auth_settings) + # body if body: body = self.sanitize_for_serialization(body) @@ -93,7 +97,7 @@ class ApiClient(object): url = self.host + resource_path # perform request and return response - response_data = self.request(method, url, query_params=query_params, headers=headers, + response_data = self.request(method, url, query_params=query_params, headers=header_params, post_params=post_params, body=body) # deserialize response data @@ -244,11 +248,12 @@ class ApiClient(object): if files: for k, v in iteritems(files): - with open(v, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - params[k] = tuple([filename, filedata, mimetype]) + if v: + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' + params[k] = tuple([filename, filedata, mimetype]) return params @@ -279,3 +284,20 @@ class ApiClient(object): return 'application/json' else: return content_types[0] + + def update_params_for_auth(self, headers, querys, auth_settings): + """ + Update header and query params based on authentication setting + """ + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = configuration.auth_settings().get(auth) + if auth_setting: + if auth_setting['in'] == 'header': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + querys[auth_setting['key']] = auth_setting['value'] + else: + raise ValueError('Authentication token must be in `query` or `header`') diff --git a/modules/swagger-codegen/src/main/resources/python/config.mustache b/modules/swagger-codegen/src/main/resources/python/config.mustache deleted file mode 100644 index e8c36aee77b..00000000000 --- a/modules/swagger-codegen/src/main/resources/python/config.mustache +++ /dev/null @@ -1,8 +0,0 @@ -from __future__ import absolute_import - -from .swagger import ApiClient - -# Configuration variables - -api_client = ApiClient("{{basePath}}") - diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache new file mode 100644 index 00000000000..d3a7093a02a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -0,0 +1,51 @@ +from __future__ import absolute_import +import base64 +import urllib3 + +def get_api_key_with_prefix(key): + global api_key + global api_key_prefix + + if api_key.get(key) and api_key_prefix.get(key): + return api_key_prefix[key] + ' ' + api_key[key] + elif api_key.get(key): + return api_key[key] + +def get_basic_auth_token(): + global username + global password + + return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization') + +def auth_settings(): + return { {{#authMethods}}{{#isApiKey}} + '{{name}}': { + 'type': 'api_key', + 'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, + 'key': '{{keyParamName}}', + 'value': get_api_key_with_prefix('{{keyParamName}}') + }, + {{/isApiKey}}{{#isBasic}} + '{{name}}': { + 'type': 'basic', + 'in': 'header', + 'key': 'Authorization', + 'value': get_basic_auth_token() + }, + {{/isBasic}}{{/authMethods}} + } + +# Default Base url +host = "{{basePath}}" + +# Default api client +api_client = None + +# Authentication settings + +api_key = {} +api_key_prefix = {} +username = '' +password = '' + + diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index da99abc2493..508f3d6693a 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -1,4 +1,10 @@ # coding: utf-8 + +""" +Credit: this file (rest.py) is modified based on rest.py in Dropbox Python SDK: +https://www.dropbox.com/developers/core/sdks/python +""" + import sys import io import json @@ -120,7 +126,7 @@ class RESTClientObject(object): r = RESTResponse(r) if r.status not in range(200, 206): - raise ErrorResponse(r) + raise ApiException(r) return self.process_response(r) @@ -157,7 +163,7 @@ class RESTClientObject(object): return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) -class ErrorResponse(Exception): +class ApiException(Exception): """ Non-2xx HTTP response """ @@ -184,7 +190,10 @@ class ErrorResponse(Exception): """ Custom error response messages """ - return "({0})\nReason: {1}\nHeader: {2}\nBody: {3}\n".\ + return "({0})\n"\ + "Reason: {1}\n"\ + "HTTP response headers: {2}\n"\ + "HTTP response body: {3}\n".\ format(self.status, self.reason, self.headers, self.body) class RESTClient(object): diff --git a/modules/swagger-codegen/src/main/resources/python/util.mustache b/modules/swagger-codegen/src/main/resources/python/util.mustache deleted file mode 100644 index 1137a5d2d23..00000000000 --- a/modules/swagger-codegen/src/main/resources/python/util.mustache +++ /dev/null @@ -1,17 +0,0 @@ -from six import iteritems - -def remove_none(obj): - if isinstance(obj, (list, tuple, set)): - return type(obj)(remove_none(x) for x in obj if x is not None) - elif isinstance(obj, dict): - return type(obj)((remove_none(k), remove_none(v)) - for k, v in iteritems(obj) if k is not None and v is not None) - else: - return obj - - -def inspect_vars(obj): - if not hasattr(obj, '__dict__'): - return obj - else: - return {k: inspect_vars(getattr(obj, k)) for k in dir(obj)} diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py index 9d4b2db3de5..3e7b51b8467 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py @@ -13,4 +13,4 @@ from .apis.pet_api import PetApi from .apis.store_api import StoreApi # import ApiClient -from .swagger import ApiClient +from .api_client import ApiClient diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py similarity index 86% rename from modules/swagger-codegen/src/main/resources/python/swagger.mustache rename to samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py index 21430c469c8..b8cc4cc2a84 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py @@ -28,6 +28,7 @@ except ImportError: # for python2 from urllib import quote +from . import configuration class ApiClient(object): """ @@ -37,7 +38,7 @@ class ApiClient(object): :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 """ - def __init__(self, host=None, header_name=None, header_value=None): + def __init__(self, host=configuration.host, header_name=None, header_value=None): self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value @@ -58,15 +59,15 @@ class ApiClient(object): self.default_headers[header_name] = header_value def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, response=None): + body=None, post_params=None, files=None, response=None, auth_settings=None): # headers parameters - headers = self.default_headers.copy() - headers.update(header_params) + header_params = header_params or {} + header_params.update(self.default_headers) if self.cookie: - headers['Cookie'] = self.cookie - if headers: - headers = self.sanitize_for_serialization(headers) + header_params['Cookie'] = self.cookie + if header_params: + header_params = self.sanitize_for_serialization(header_params) # path parameters if path_params: @@ -85,6 +86,9 @@ class ApiClient(object): post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) + # auth setting + self.update_params_for_auth(header_params, query_params, auth_settings) + # body if body: body = self.sanitize_for_serialization(body) @@ -93,7 +97,7 @@ class ApiClient(object): url = self.host + resource_path # perform request and return response - response_data = self.request(method, url, query_params=query_params, headers=headers, + response_data = self.request(method, url, query_params=query_params, headers=header_params, post_params=post_params, body=body) # deserialize response data @@ -244,11 +248,12 @@ class ApiClient(object): if files: for k, v in iteritems(files): - with open(v, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - params[k] = tuple([filename, filedata, mimetype]) + if v: + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' + params[k] = tuple([filename, filedata, mimetype]) return params @@ -279,3 +284,20 @@ class ApiClient(object): return 'application/json' else: return content_types[0] + + def update_params_for_auth(self, headers, querys, auth_settings): + """ + Update header and query params based on authentication setting + """ + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = configuration.auth_settings().get(auth) + if auth_setting: + if auth_setting['in'] == 'header': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + querys[auth_setting['key']] = auth_setting['value'] + else: + raise ValueError('Authentication token must be in `query` or `header`') diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py index ad4bad57412..549b7fe956f 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py @@ -27,9 +27,8 @@ import os # python 2 and python 3 compatibility library from six import iteritems -from ..util import remove_none - -from .. import config +from .. import configuration +from ..api_client import ApiClient class PetApi(object): @@ -37,7 +36,10 @@ class PetApi(object): if api_client: self.api_client = api_client else: - self.api_client = config.api_client + if not configuration.api_client: + configuration.api_client = ApiClient('http://petstore.swagger.io/v2') + self.api_client = configuration.api_client + def update_pet(self, **kwargs): """ @@ -61,13 +63,20 @@ class PetApi(object): resource_path = '/pet'.replace('{format}', 'json') method = 'PUT' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -76,9 +85,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json', 'application/xml']) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def add_pet(self, **kwargs): """ @@ -102,13 +114,20 @@ class PetApi(object): resource_path = '/pet'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -117,9 +136,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json', 'application/xml']) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def find_pets_by_status(self, **kwargs): """ @@ -143,13 +165,20 @@ class PetApi(object): resource_path = '/pet/findByStatus'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict()) - query_params = remove_none(dict(status=params.get('status'))) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + query_params = {} + + if 'status' in params: + query_params['status'] = params['status'] + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -158,9 +187,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='list[Pet]') + response='list[Pet]', auth_settings=auth_settings) return response @@ -186,13 +218,20 @@ class PetApi(object): resource_path = '/pet/findByTags'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict()) - query_params = remove_none(dict(tags=params.get('tags'))) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + query_params = {} + + if 'tags' in params: + query_params['tags'] = params['tags'] + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -201,9 +240,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='list[Pet]') + response='list[Pet]', auth_settings=auth_settings) return response @@ -233,13 +275,20 @@ class PetApi(object): resource_path = '/pet/{petId}'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict(petId=params.get('pet_id'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + if 'pet_id' in params: + path_params['petId'] = params['pet_id'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -248,9 +297,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = ['api_key', 'petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='Pet') + response='Pet', auth_settings=auth_settings) return response @@ -282,13 +334,26 @@ class PetApi(object): resource_path = '/pet/{petId}'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict(petId=params.get('pet_id'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict(name=params.get('name'), status=params.get('status'))) - files = remove_none(dict()) + path_params = {} + + if 'pet_id' in params: + path_params['petId'] = params['pet_id'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + if 'name' in params: + form_params['name'] = params['name'] + + if 'status' in params: + form_params['status'] = params['status'] + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -297,9 +362,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type(['application/x-www-form-urlencoded']) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def delete_pet(self, pet_id, **kwargs): """ @@ -328,13 +396,23 @@ class PetApi(object): resource_path = '/pet/{petId}'.replace('{format}', 'json') method = 'DELETE' - path_params = remove_none(dict(petId=params.get('pet_id'))) - query_params = remove_none(dict()) - header_params = remove_none(dict(api_key=params.get('api_key'))) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + if 'pet_id' in params: + path_params['petId'] = params['pet_id'] + + query_params = {} + + header_params = {} + + if 'api_key' in params: + header_params['api_key'] = params['api_key'] + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -343,9 +421,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def upload_file(self, pet_id, **kwargs): """ @@ -375,13 +456,26 @@ class PetApi(object): resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict(petId=params.get('pet_id'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict(additionalMetadata=params.get('additional_metadata'), )) - files = remove_none(dict(file=params.get('file'))) + path_params = {} + + if 'pet_id' in params: + path_params['petId'] = params['pet_id'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + if 'additional_metadata' in params: + form_params['additionalMetadata'] = params['additional_metadata'] + + if 'file' in params: + files['file'] = params['file'] + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -390,9 +484,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type(['multipart/form-data']) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py index e973d3a6ba5..bd2fd9b8080 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py @@ -27,9 +27,8 @@ import os # python 2 and python 3 compatibility library from six import iteritems -from ..util import remove_none - -from .. import config +from .. import configuration +from ..api_client import ApiClient class StoreApi(object): @@ -37,7 +36,10 @@ class StoreApi(object): if api_client: self.api_client = api_client else: - self.api_client = config.api_client + if not configuration.api_client: + configuration.api_client = ApiClient('http://petstore.swagger.io/v2') + self.api_client = configuration.api_client + def get_inventory(self, **kwargs): """ @@ -60,13 +62,17 @@ class StoreApi(object): resource_path = '/store/inventory'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -75,9 +81,12 @@ class StoreApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = ['api_key'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='map(String, int)') + response='map(String, int)', auth_settings=auth_settings) return response @@ -103,13 +112,20 @@ class StoreApi(object): resource_path = '/store/order'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -118,9 +134,12 @@ class StoreApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='Order') + response='Order', auth_settings=auth_settings) return response @@ -150,13 +169,20 @@ class StoreApi(object): resource_path = '/store/order/{orderId}'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict(orderId=params.get('order_id'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + if 'order_id' in params: + path_params['orderId'] = params['order_id'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -165,9 +191,12 @@ class StoreApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='Order') + response='Order', auth_settings=auth_settings) return response @@ -197,13 +226,20 @@ class StoreApi(object): resource_path = '/store/order/{orderId}'.replace('{format}', 'json') method = 'DELETE' - path_params = remove_none(dict(orderId=params.get('order_id'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + if 'order_id' in params: + path_params['orderId'] = params['order_id'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -212,9 +248,12 @@ class StoreApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py index 82874000d59..5aca93818d0 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py @@ -27,9 +27,8 @@ import os # python 2 and python 3 compatibility library from six import iteritems -from ..util import remove_none - -from .. import config +from .. import configuration +from ..api_client import ApiClient class UserApi(object): @@ -37,7 +36,10 @@ class UserApi(object): if api_client: self.api_client = api_client else: - self.api_client = config.api_client + if not configuration.api_client: + configuration.api_client = ApiClient('http://petstore.swagger.io/v2') + self.api_client = configuration.api_client + def create_user(self, **kwargs): """ @@ -61,13 +63,20 @@ class UserApi(object): resource_path = '/user'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -76,9 +85,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def create_users_with_array_input(self, **kwargs): """ @@ -102,13 +114,20 @@ class UserApi(object): resource_path = '/user/createWithArray'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -117,9 +136,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def create_users_with_list_input(self, **kwargs): """ @@ -143,13 +165,20 @@ class UserApi(object): resource_path = '/user/createWithList'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -158,9 +187,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def login_user(self, **kwargs): """ @@ -185,13 +217,23 @@ class UserApi(object): resource_path = '/user/login'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict()) - query_params = remove_none(dict(username=params.get('username'), password=params.get('password'))) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + query_params = {} + + if 'username' in params: + query_params['username'] = params['username'] + + if 'password' in params: + query_params['password'] = params['password'] + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -200,9 +242,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='str') + response='str', auth_settings=auth_settings) return response @@ -227,13 +272,17 @@ class UserApi(object): resource_path = '/user/logout'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -242,9 +291,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def get_user_by_name(self, username, **kwargs): """ @@ -272,13 +324,20 @@ class UserApi(object): resource_path = '/user/{username}'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict(username=params.get('username'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + if 'username' in params: + path_params['username'] = params['username'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -287,9 +346,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='User') + response='User', auth_settings=auth_settings) return response @@ -320,13 +382,23 @@ class UserApi(object): resource_path = '/user/{username}'.replace('{format}', 'json') method = 'PUT' - path_params = remove_none(dict(username=params.get('username'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + if 'username' in params: + path_params['username'] = params['username'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -335,9 +407,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def delete_user(self, username, **kwargs): """ @@ -365,13 +440,20 @@ class UserApi(object): resource_path = '/user/{username}'.replace('{format}', 'json') method = 'DELETE' - path_params = remove_none(dict(username=params.get('username'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + if 'username' in params: + path_params['username'] = params['username'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -380,9 +462,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py deleted file mode 100644 index 6e158eedd70..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py +++ /dev/null @@ -1,8 +0,0 @@ -from __future__ import absolute_import - -from .swagger import ApiClient - -# Configuration variables - -api_client = ApiClient("http://petstore.swagger.io/v2") - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/configuration.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/configuration.py new file mode 100644 index 00000000000..b5bd0a64e0a --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/configuration.py @@ -0,0 +1,44 @@ +from __future__ import absolute_import +import base64 +import urllib3 + +def get_api_key_with_prefix(key): + global api_key + global api_key_prefix + + if api_key.get(key) and api_key_prefix.get(key): + return api_key_prefix[key] + ' ' + api_key[key] + elif api_key.get(key): + return api_key[key] + +def get_basic_auth_token(): + global username + global password + + return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization') + +def auth_settings(): + return { + 'api_key': { + 'type': 'api_key', + 'in': 'header', + 'key': 'api_key', + 'value': get_api_key_with_prefix('api_key') + }, + + } + +# Default Base url +host = "http://petstore.swagger.io/v2" + +# Default api client +api_client = None + +# Authentication settings + +api_key = {} +api_key_prefix = {} +username = '' +password = '' + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py index da99abc2493..508f3d6693a 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py @@ -1,4 +1,10 @@ # coding: utf-8 + +""" +Credit: this file (rest.py) is modified based on rest.py in Dropbox Python SDK: +https://www.dropbox.com/developers/core/sdks/python +""" + import sys import io import json @@ -120,7 +126,7 @@ class RESTClientObject(object): r = RESTResponse(r) if r.status not in range(200, 206): - raise ErrorResponse(r) + raise ApiException(r) return self.process_response(r) @@ -157,7 +163,7 @@ class RESTClientObject(object): return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) -class ErrorResponse(Exception): +class ApiException(Exception): """ Non-2xx HTTP response """ @@ -184,7 +190,10 @@ class ErrorResponse(Exception): """ Custom error response messages """ - return "({0})\nReason: {1}\nHeader: {2}\nBody: {3}\n".\ + return "({0})\n"\ + "Reason: {1}\n"\ + "HTTP response headers: {2}\n"\ + "HTTP response body: {3}\n".\ format(self.status, self.reason, self.headers, self.body) class RESTClient(object): diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py deleted file mode 100644 index 1137a5d2d23..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py +++ /dev/null @@ -1,17 +0,0 @@ -from six import iteritems - -def remove_none(obj): - if isinstance(obj, (list, tuple, set)): - return type(obj)(remove_none(x) for x in obj if x is not None) - elif isinstance(obj, dict): - return type(obj)((remove_none(k), remove_none(v)) - for k, v in iteritems(obj) if k is not None and v is not None) - else: - return obj - - -def inspect_vars(obj): - if not hasattr(obj, '__dict__'): - return obj - else: - return {k: inspect_vars(getattr(obj, k)) for k in dir(obj)} diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py index 5243430a93a..0ef4314d0f4 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py @@ -12,6 +12,7 @@ import time import unittest import SwaggerPetstore +import SwaggerPetstore.configuration HOST = 'http://petstore.swagger.io/v2' @@ -21,6 +22,31 @@ class ApiClientTests(unittest.TestCase): def setUp(self): self.api_client = SwaggerPetstore.ApiClient(HOST) + def test_configuration(self): + SwaggerPetstore.configuration.api_key['api_key'] = '123456' + SwaggerPetstore.configuration.api_key_prefix['api_key'] = 'PREFIX' + SwaggerPetstore.configuration.username = 'test_username' + SwaggerPetstore.configuration.password = 'test_password' + + header_params = {'test1': 'value1'} + query_params = {'test2': 'value2'} + auth_settings = ['api_key', 'unknown'] + + # test prefix + self.assertEqual('PREFIX', SwaggerPetstore.configuration.api_key_prefix['api_key']) + + # update parameters based on auth setting + self.api_client.update_params_for_auth(header_params, query_params, auth_settings) + + # test api key auth + self.assertEqual(header_params['test1'], 'value1') + self.assertEqual(header_params['api_key'], 'PREFIX 123456') + self.assertEqual(query_params['test2'], 'value2') + + # test basic auth + self.assertEqual('test_username', SwaggerPetstore.configuration.username) + self.assertEqual('test_password', SwaggerPetstore.configuration.password) + def test_select_header_accept(self): accepts = ['APPLICATION/JSON', 'APPLICATION/XML'] accept = self.api_client.select_header_accept(accepts) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py new file mode 100644 index 00000000000..d1b786241e8 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py @@ -0,0 +1,76 @@ +# coding: utf-8 + +""" +Run the tests. +$ pip install nose (optional) +$ cd SwaggerPetstore-python +$ nosetests -v +""" + +import os +import time +import unittest + +import SwaggerPetstore +from SwaggerPetstore.rest import ApiException + + +class ApiExceptionTests(unittest.TestCase): + + def setUp(self): + self.api_client = SwaggerPetstore.ApiClient() + self.pet_api = SwaggerPetstore.PetApi(self.api_client) + self.setUpModels() + + def setUpModels(self): + self.category = SwaggerPetstore.Category() + self.category.id = int(time.time()) + self.category.name = "dog" + self.tag = SwaggerPetstore.Tag() + self.tag.id = int(time.time()) + self.tag.name = "blank" + self.pet = SwaggerPetstore.Pet() + self.pet.id = int(time.time()) + self.pet.name = "hello kity" + self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] + self.pet.status = "sold" + self.pet.category = self.category + self.pet.tags = [self.tag] + + def tearDown(self): + time.sleep(1) + + def test_404_error(self): + self.pet_api.add_pet(body=self.pet) + self.pet_api.delete_pet(pet_id=self.pet.id) + + with self.assertRaisesRegexp(ApiException, "Pet not found"): + self.pet_api.get_pet_by_id(pet_id=self.pet.id) + + try: + self.pet_api.get_pet_by_id(pet_id=self.pet.id) + except ApiException as e: + self.assertEqual(e.status, 404) + self.assertEqual(e.reason, "Not Found") + self.assertDictEqual(e.body, {'message': 'Pet not found', 'code': 1, 'type': 'error'}) + + def test_500_error(self): + self.pet_api.add_pet(body=self.pet) + + with self.assertRaisesRegexp(ApiException, "Internal Server Error"): + self.pet_api.upload_file( + pet_id=self.pet.id, + additional_metadata="special", + file=None + ) + + try: + self.pet_api.upload_file( + pet_id=self.pet.id, + additional_metadata="special", + file=None + ) + except ApiException as e: + self.assertEqual(e.status, 500) + self.assertEqual(e.reason, "Internal Server Error") + self.assertRegexpMatches(e.body, "Error 500 Internal Server Error") diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py index ee8c5dde14e..3bf18607729 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py @@ -12,8 +12,7 @@ import time import unittest import SwaggerPetstore -from SwaggerPetstore.rest import ErrorResponse -from SwaggerPetstore import config +from SwaggerPetstore.rest import ApiException HOST = 'http://petstore.swagger.io/v2' @@ -62,11 +61,11 @@ class PetApiTests(unittest.TestCase): # same default api client self.assertEqual(pet_api.api_client, pet_api2.api_client) # confirm using the default api client in the config module - self.assertEqual(pet_api.api_client, config.api_client) + self.assertEqual(pet_api.api_client, SwaggerPetstore.configuration.api_client) # 2 different api clients are not the same self.assertNotEqual(api_client3, api_client4) # customized pet api not using the default api client - self.assertNotEqual(pet_api3.api_client, config.api_client) + self.assertNotEqual(pet_api3.api_client, SwaggerPetstore.configuration.api_client) # customized pet api not using the old pet api's api client self.assertNotEqual(pet_api3.api_client, pet_api2.api_client) @@ -126,7 +125,7 @@ class PetApiTests(unittest.TestCase): additional_metadata=additional_metadata, file=self.foo ) - except ErrorResponse as e: + except ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) def test_delete_pet(self): @@ -136,7 +135,7 @@ class PetApiTests(unittest.TestCase): try: self.pet_api.get_pet_by_id(pet_id=self.pet.id) raise "expected an error" - except ErrorResponse as e: + except ApiException as e: self.assertEqual(404, e.status) if __name__ == '__main__':