Merge pull request #923 from xhh/ruby-debug

[Ruby] Some improvements & cleaning-up on Ruby API client
This commit is contained in:
wing328 2015-07-14 16:34:41 +08:00
commit 7242a664e3
45 changed files with 749 additions and 807 deletions

5
bin/ruby-petstore.json Normal file
View File

@ -0,0 +1,5 @@
{
"gemName": "petstore",
"moduleName": "Petstore",
"gemVersion": "1.0.0"
}

View File

@ -26,6 +26,6 @@ fi
# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/ruby -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l ruby -o samples/client/petstore/ruby"
ags="$@ generate -t modules/swagger-codegen/src/main/resources/ruby -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l ruby -c bin/ruby-petstore.json -o samples/client/petstore/ruby"
java $JAVA_OPTS -jar $executable $ags

View File

@ -1,10 +1,18 @@
package io.swagger.codegen;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
public class CodegenParameter {
public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam,
isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam;
public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue;
public String jsonSchema;
public boolean isEnum;
public List<String> _enum;
public Map<String, Object> allowableValues;
/**
* Determines whether this parameter is mandatory. If the parameter is in "path",
@ -35,6 +43,13 @@ public class CodegenParameter {
output.required = this.required;
output.jsonSchema = this.jsonSchema;
output.defaultValue = this.defaultValue;
output.isEnum = this.isEnum;
if (this._enum != null) {
output._enum = new ArrayList<String>(this._enum);
}
if (this.allowableValues != null) {
output.allowableValues = new HashMap<String, Object>(this.allowableValues);
}
return output;
}

View File

@ -37,6 +37,7 @@ import io.swagger.models.properties.LongProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.PropertyBuilder;
import io.swagger.models.properties.PropertyBuilder.PropertyId;
import io.swagger.models.properties.RefProperty;
import io.swagger.models.properties.StringProperty;
import io.swagger.util.Json;
@ -977,7 +978,9 @@ public class DefaultCodegen {
p.baseType = pr.datatype;
imports.add(pr.baseType);
} else {
property = PropertyBuilder.build(qp.getType(), qp.getFormat(), null);
Map<PropertyId, Object> args = new HashMap<PropertyId, Object>();
args.put(PropertyId.ENUM, qp.getEnum());
property = PropertyBuilder.build(qp.getType(), qp.getFormat(), args);
}
if (property == null) {
LOGGER.warn("warning! Property type \"" + qp.getType() + "\" not found for parameter \"" + param.getName() + "\", using String");
@ -985,8 +988,11 @@ public class DefaultCodegen {
}
property.setRequired(param.getRequired());
CodegenProperty model = fromProperty(qp.getName(), property);
p.collectionFormat = collectionFormat;
p.dataType = model.datatype;
p.isEnum = model.isEnum;
p._enum = model._enum;
p.allowableValues = model.allowableValues;
p.collectionFormat = collectionFormat;
p.paramName = toParamName(qp.getName());
if (model.complexType != null) {

View File

@ -219,7 +219,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
bundle.put("models", allModels);
bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar));
bundle.put("modelPackage", config.modelPackage());
bundle.put("authMethods", config.fromSecurity(swagger.getSecurityDefinitions()));
List<CodegenSecurity> authMethods = config.fromSecurity(swagger.getSecurityDefinitions());
if (!authMethods.isEmpty()) {
bundle.put("authMethods", authMethods);
bundle.put("hasAuthMethods", true);
}
if (swagger.getExternalDocs() != null) {
bundle.put("externalDocs", swagger.getExternalDocs());
}

View File

@ -55,6 +55,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("float", "Float");
typeMapping.put("double", "Float");
typeMapping.put("number", "Float");
typeMapping.put("date", "Date");
typeMapping.put("DateTime", "DateTime");
typeMapping.put("boolean", "BOOLEAN");
typeMapping.put("array", "Array");
@ -107,7 +108,6 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec"));
supportingFiles.add(new SupportingFile("swagger_client.mustache", libFolder, gemName + ".rb"));
String baseFolder = libFolder + File.separator + gemName;
supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb"));
supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb"));
String swaggerFolder = baseFolder + File.separator + "swagger";
supportingFiles.add(new SupportingFile("swagger" + File.separator + "request.mustache", swaggerFolder, "request.rb"));

View File

@ -3,8 +3,6 @@ require "uri"
module {{moduleName}}
{{#operations}}
class {{classname}}
basePath = "{{basePath}}"
# apiInvoker = APIInvoker
{{#operation}}
{{newline}}
# {{summary}}
@ -14,11 +12,20 @@ module {{moduleName}}
{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}}
{{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}]
def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: {{classname}}#{{nickname}} ..."
end
{{#allParams}}{{#required}}
# verify the required parameter '{{paramName}}' is set
raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil?
{{/required}}{{/allParams}}
fail "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil?{{#isEnum}}
unless [{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?({{{paramName}}})
fail "invalid value for '{{{paramName}}}', must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}"
end{{/isEnum}}
{{/required}}{{^required}}{{#isEnum}}
if opts[:'{{{paramName}}}'] && ![{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?(opts[:'{{{paramName}}}'])
fail 'invalid value for "{{{paramName}}}", must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}'
end
{{/isEnum}}{{/required}}{{/allParams}}
# resource path
path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}}
@ -52,7 +59,14 @@ module {{moduleName}}
auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]
{{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
response.deserialize('{{{returnType}}}'){{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
result = response.deserialize('{{{returnType}}}')
if Swagger.configuration.debug
Swagger.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}"
end
result{{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: {{classname}}#{{nickname}}"
end
nil{{/returnType}}
end
{{/operation}}

View File

@ -1,3 +1,5 @@
require 'date'
module {{moduleName}}
# base class containing fundamental method such as to_hash, build_from_hash and more
class BaseObject
@ -26,6 +28,8 @@ module {{moduleName}}
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer

View File

@ -29,11 +29,20 @@ module {{moduleName}}
{{#vars}}
if attributes[:'{{{baseName}}}']
{{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array)
@{{{name}}} = value
end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}}
self.{{{name}}} = value
end{{/isContainer}}{{^isContainer}}self.{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}}
end
{{/vars}}
end
{{#vars}}{{#isEnum}}
def {{{name}}}=({{{name}}})
allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]
if {{{name}}} && !allowed_values.include?({{{name}}})
fail "invalid value for '{{{name}}}', must be one of #{allowed_values}"
end
@{{{name}}} = {{{name}}}
end
{{/isEnum}}{{/vars}}
end
{{/model}}
{{/models}}

View File

@ -1,82 +0,0 @@
class Object
unless Object.method_defined? :blank?
def blank?
respond_to?(:empty?) ? empty? : !self
end
end
unless Object.method_defined? :present?
def present?
!blank?
end
end
end
class String
unless String.method_defined? :underscore
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
unless String.method_defined? :camelize
def camelize(first_letter_in_uppercase = true)
if first_letter_in_uppercase != :lower
self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
else
self.to_s[0].chr.downcase + camelize(self)[1..-1]
end
end
end
end
class Hash
unless Hash.method_defined? :stringify_keys
def stringify_keys
inject({}) do |options, (key, value)|
options[key.to_s] = value
options
end
end
end
unless Hash.method_defined? :stringify_keys!
def stringify_keys!
self.replace(self.stringify_keys)
end
end
unless Hash.method_defined? :symbolize_keys
def symbolize_keys
inject({}) do |options, (key, value)|
options[(key.to_sym rescue key) || key] = value
options
end
end
end
unless Hash.method_defined? :symbolize_keys!
def symbolize_keys!
self.replace(self.symbolize_keys)
end
end
unless Hash.method_defined? :symbolize_and_underscore_keys
def symbolize_and_underscore_keys
inject({}) do |options, (key, value)|
options[(key.to_s.underscore.to_sym rescue key) || key] = value
options
end
end
end
unless Hash.method_defined? :symbolize_and_underscore_keys!
def symbolize_and_underscore_keys!
self.replace(self.symbolize_and_underscore_keys)
end
end
end

View File

@ -1,6 +1,3 @@
require 'logger'
require 'json'
module {{moduleName}}
module Swagger
class << self
@ -25,8 +22,7 @@ module {{moduleName}}
def configure
yield(configuration) if block_given?
# Configure logger. Default to use Rails
self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT))
self.logger = configuration.logger
# remove :// from scheme
configuration.scheme.sub!(/:\/\//, '')
@ -41,7 +37,7 @@ module {{moduleName}}
end
def authenticated?
Swagger.configuration.auth_token.present?
!Swagger.configuration.auth_token.nil?
end
def de_authenticate
@ -51,7 +47,7 @@ module {{moduleName}}
def authenticate
return if Swagger.authenticated?
if Swagger.configuration.username.blank? || Swagger.configuration.password.blank?
if Swagger.configuration.username.nil? || Swagger.configuration.password.nil?
raise ApiError, "Username and password are required to authenticate."
end
@ -67,6 +63,14 @@ module {{moduleName}}
response_body = request.response.body
Swagger.configuration.auth_token = response_body['token']
end
def last_response
Thread.current[:swagger_last_response]
end
def last_response=(response)
Thread.current[:swagger_last_response] = response
end
end
end
end

View File

@ -1,7 +1,64 @@
require 'logger'
module {{moduleName}}
module Swagger
class Configuration
attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl
attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format
# Defines the username used with HTTP basic authentication.
#
# @return [String]
attr_accessor :username
# Defines the password used with HTTP basic authentication.
#
# @return [String]
attr_accessor :password
# Defines API keys used with API Key authentications.
#
# @return [Hash] key: parameter name, value: parameter value (API key)
#
# @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
# config.api_key['api_key'] = 'xxx'
attr_accessor :api_key
# Defines API key prefixes used with API Key authentications.
#
# @return [Hash] key: parameter name, value: API key prefix
#
# @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
# config.api_key_prefix['api_key'] = 'Token'
attr_accessor :api_key_prefix
# Set this to false to skip verifying SSL certificate when calling API from https server.
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :verify_ssl
# Set this to customize the certificate file to verify the peer.
#
# @return [String] the path to the certificate file
#
# @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
# https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
attr_accessor :ssl_ca_cert
# Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
# details will be logged with `logger.debug` (see the `logger` attribute).
# Default to false.
#
# @return [true, false]
attr_accessor :debug
# Defines the logger used for debugging.
# Default to `Rails.logger` (when in Rails) or logging to STDOUT.
#
# @return [#debug]
attr_accessor :logger
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
@ -24,7 +81,6 @@ module {{moduleName}}
@user_agent = "ruby-swagger-#{Swagger::VERSION}"
@inject_format = false
@force_ending_format = false
@camelize_params = true
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
@ -33,13 +89,12 @@ module {{moduleName}}
# keys for API key authentication (param-name => api-key)
@api_key = {}
# api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix)
@api_key_prefix = {}
# whether to verify SSL certificate, default to true
# Note: do NOT set it to false in production code, otherwise you would
# face multiple types of cryptographic attacks
@verify_ssl = true
@debug = false
@logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
end
end
end

View File

@ -1,21 +1,18 @@
require 'uri'
require 'typhoeus'
module {{moduleName}}
module Swagger
class Request
require 'uri'
require 'addressable/uri'
require 'typhoeus'
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response
# All requests must have an HTTP method and a path
# Optionals parameters are :params, :headers, :body, :format, :host
def initialize(http_method, path, attributes={})
@http_method = http_method.to_sym
def initialize(http_method, path, attributes = {})
@http_method = http_method.to_sym.downcase
@path = path
attributes.each do |name, value|
send("#{name.to_s.underscore.to_sym}=", value)
end
attributes.each { |name, value| send "#{name}=", value }
@format ||= Swagger.configuration.format
@params ||= {}
@ -27,10 +24,12 @@ module {{moduleName}}
if Swagger.authenticated?
@headers.merge!({:auth_token => Swagger.configuration.auth_token})
end
{{#hasAuthMethods}}
update_params_for_auth!
{{/hasAuthMethods}}
end
{{#hasAuthMethods}}
# Update hearder and query params based on authentication settings.
def update_params_for_auth!
(@auth_names || []).each do |auth_name|
@ -45,30 +44,23 @@ module {{moduleName}}
end
end
end
{{/hasAuthMethods}}
# Get API key (with prefix if set).
# @param [String] param_name the parameter name of API key auth
def get_api_key_with_prefix(param_name)
if Swagger.configuration.api_key_prefix[param_name].present?
if Swagger.configuration.api_key_prefix[param_name]
"#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}"
else
Swagger.configuration.api_key[param_name]
end
end
# Construct a base URL
# Construct the request URL.
def url(options = {})
u = Addressable::URI.new(
:scheme => Swagger.configuration.scheme,
:host => Swagger.configuration.host,
:path => self.interpreted_path,
:query => self.query_string.sub(/\?/, '')
).to_s
# Drop trailing question mark, if present
u.sub! /\?$/, ''
u
_path = self.interpreted_path
_path = "/#{_path}" unless _path.start_with?('/')
"#{Swagger.configuration.scheme}://#{Swagger.configuration.host}#{_path}"
end
# Iterate over the params hash, injecting any path values into the path string
@ -99,18 +91,6 @@ module {{moduleName}}
URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/')
end
# Massage the request body into a state of readiness
# If body is a hash, camelize all keys then convert to a json string
def body=(value)
if value.is_a?(Hash)
value = value.inject({}) do |memo, (k,v)|
memo[k.to_s.camelize(:lower).to_sym] = v
memo
end
end
@body = value
end
# If body is an object, JSONify it before making the actual request.
# For form parameters, remove empty value
def outgoing_body
@ -120,93 +100,60 @@ module {{moduleName}}
data.each do |key, value|
data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter
end
data
elsif @body # http body is JSON
@body.is_a?(String) ? @body : @body.to_json
data = @body.is_a?(String) ? @body : @body.to_json
else
nil
end
end
# Construct a query string from the query-string-type params
def query_string
# Iterate over all params,
# .. removing the ones that are part of the path itself.
# .. stringifying values so Addressable doesn't blow up.
query_values = {}
self.params.each_pair do |key, value|
next if self.path.include? "{#{key}}" # skip path params
next if value.blank? && value.class != FalseClass # skip empties
if Swagger.configuration.camelize_params
key = key.to_s.camelize(:lower).to_sym
end
query_values[key] = value.to_s
data = nil
end
# We don't want to end up with '?' as our query string
# if there aren't really any params
return "" if query_values.blank?
if Swagger.configuration.debug
Swagger.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n"
end
# Addressable requires query_values to be set after initialization..
qs = Addressable::URI.new
qs.query_values = query_values
qs.to_s
data
end
def make
#TODO use configuration setting to determine if debugging
#logger = Logger.new STDOUT
#logger.debug self.url
request_options = {
:method => self.http_method,
:headers => self.headers,
:params => self.params,
:ssl_verifypeer => Swagger.configuration.verify_ssl,
:headers => self.headers.stringify_keys
:cainfo => Swagger.configuration.ssl_ca_cert,
:verbose => Swagger.configuration.debug
}
response = case self.http_method.to_sym
when :get,:GET
Typhoeus::Request.get(
self.url,
request_options
)
when :post,:POST
Typhoeus::Request.post(
self.url,
request_options.merge(:body => self.outgoing_body)
)
when :patch,:PATCH
Typhoeus::Request.patch(
self.url,
request_options.merge(:body => self.outgoing_body)
)
when :put,:PUT
Typhoeus::Request.put(
self.url,
request_options.merge(:body => self.outgoing_body)
)
when :delete,:DELETE
Typhoeus::Request.delete(
self.url,
request_options.merge(:body => self.outgoing_body)
)
if [:post, :patch, :put, :delete].include?(self.http_method)
request_options.update :body => self.outgoing_body
end
Response.new(response)
end
def response
self.make
raw = Typhoeus::Request.new(self.url, request_options).run
@response = Response.new(raw)
if Swagger.configuration.debug
Swagger.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n"
end
# record as last response
Swagger.last_response = @response
unless @response.success?
fail ApiError.new(:code => @response.code,
:response_headers => @response.headers,
:response_body => @response.body),
@response.status_message
end
@response
end
def response_code_pretty
return unless @response.present?
return unless @response
@response.code.to_s
end
def response_headers_pretty
return unless @response.present?
return unless @response
# JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient
@response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
end

View File

@ -9,28 +9,29 @@ module {{moduleName}}
def initialize(raw)
self.raw = raw
unless raw.success?
fail ApiError.new(:code => code,
:response_headers => headers,
:response_body => body),
raw.status_message
end
end
def code
raw.code
end
def status_message
raw.status_message
end
def body
raw.body
end
def success?
raw.success?
end
# Deserialize the raw response body to the given return type.
#
# @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
def deserialize(return_type)
return nil if body.blank?
return nil if body.nil? || body.empty?
# handle file downloading - save response body into a tmp file and return the File instance
return download_file if return_type == 'File'
@ -43,40 +44,48 @@ module {{moduleName}}
end
begin
data = JSON.parse(body, :symbolize_names => true)
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if return_type == 'String'
return body
if %w(String Date DateTime).include?(return_type)
data = body
else
raise e
end
end
build_models data, return_type
convert_to_type data, return_type
end
# Walk through the given data and, when necessary, build model(s) from
# Hash data for array/hash values of the response.
def build_models(data, return_type)
# Convert data to the given return type.
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String', 'Integer', 'Float', 'BOOLEAN'
# primitives, return directly
data
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'BOOLEAN'
data == true
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
when 'Date'
# parse date time (expecting ISO 8601 format)
Date.parse data
when 'Object'
# generic object, return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map {|item| build_models(item, sub_type) }
data.map {|item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each {|k, v| hash[k] = build_models(v, sub_type) }
data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models, e.g. Pet
@ -131,9 +140,11 @@ module {{moduleName}}
end
def pretty_body
return unless body.present?
case format
when 'json' then JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>')
return unless body
if format == 'json'
JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>')
else
body
end
end

View File

@ -14,7 +14,6 @@ Gem::Specification.new do |s|
s.license = "Apache-2.0"
s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1'
s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4'
s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6'
s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0'

View File

@ -1,5 +1,4 @@
# Swagger common files
require '{{gemName}}/monkey'
require '{{gemName}}/swagger'
require '{{gemName}}/swagger/configuration'
require '{{gemName}}/swagger/api_error'

View File

@ -1,8 +1,7 @@
PATH
remote: .
specs:
swagger_client (1.0.0)
addressable (~> 2.2, >= 2.2.4)
petstore (1.0.0)
json (~> 1.4, >= 1.4.6)
typhoeus (~> 0.2, >= 0.2.1)
@ -55,7 +54,7 @@ DEPENDENCIES
autotest-fsevent (~> 0.2, >= 0.2.10)
autotest-growl (~> 0.2, >= 0.2.16)
autotest-rails-pure (~> 4.1, >= 4.1.2)
petstore!
rspec (~> 3.2, >= 3.2.0)
swagger_client!
vcr (~> 2.9, >= 2.9.3)
webmock (~> 1.6, >= 1.6.2)

View File

@ -5,20 +5,20 @@
You can build the generated client into a gem:
```shell
gem build swagger_client.gemspec
gem build petstore.gemspec
```
Then you can either install the gem:
```shell
gem install ./swagger_client-1.0.0.gem
gem install ./petstore-1.0.0.gem
```
or publish the gem to a gem server like [RubyGems](https://rubygems.org/).
Finally add this to your Gemfile:
gem 'swagger_client', '~> 1.0.0'
gem 'petstore', '~> 1.0.0'
### Host as a git repository
@ -27,7 +27,7 @@ https://github.com/xhh/swagger-petstore-ruby
Then you can reference it in Gemfile:
gem 'swagger_client', :git => 'https://github.com/xhh/swagger-petstore-ruby.git'
gem 'petstore', :git => 'https://github.com/xhh/swagger-petstore-ruby.git'
### Use without installation
@ -40,18 +40,20 @@ ruby -Ilib script.rb
## Configuration
```ruby
require 'swagger_client'
require 'petstore'
SwaggerClient::Swagger.configure do |config|
config.api_key = 'special-key'
Petstore::Swagger.configure do |config|
config.api_key['api_key'] = 'special-key'
config.host = 'petstore.swagger.io'
config.base_path = '/v2'
# enable debugging (default is false)
config.debug = true
end
```
## Getting Started
```ruby
pet = SwaggerClient::PetApi.get_pet_by_id(5)
pet = Petstore::PetApi.get_pet_by_id(5)
puts pet.to_body
```

View File

@ -0,0 +1,26 @@
# Swagger common files
require 'petstore/swagger'
require 'petstore/swagger/configuration'
require 'petstore/swagger/api_error'
require 'petstore/swagger/request'
require 'petstore/swagger/response'
require 'petstore/swagger/version'
# Models
require 'petstore/models/base_object'
require 'petstore/models/user'
require 'petstore/models/category'
require 'petstore/models/pet'
require 'petstore/models/tag'
require 'petstore/models/order'
# APIs
require 'petstore/api/user_api'
require 'petstore/api/pet_api'
require 'petstore/api/store_api'
module Petstore
# Initialize the default configuration
Swagger.configuration = Swagger::Configuration.new
Swagger.configure { |config| }
end

View File

@ -1,9 +1,7 @@
require "uri"
module SwaggerClient
module Petstore
class PetApi
basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker
# Update an existing pet
#
@ -11,8 +9,10 @@ module SwaggerClient
# @option opts [Pet] :body Pet object that needs to be added to the store
# @return [nil]
def self.update_pet(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#update_pet ..."
end
# resource path
path = "/pet".sub('{format}','json')
@ -38,7 +38,10 @@ module SwaggerClient
auth_names = ['petstore_auth']
Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
Swagger::Request.new(:PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#update_pet"
end
nil
end
@ -48,8 +51,10 @@ module SwaggerClient
# @option opts [Pet] :body Pet object that needs to be added to the store
# @return [nil]
def self.add_pet(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#add_pet ..."
end
# resource path
path = "/pet".sub('{format}','json')
@ -75,7 +80,10 @@ module SwaggerClient
auth_names = ['petstore_auth']
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#add_pet"
end
nil
end
@ -85,8 +93,10 @@ module SwaggerClient
# @option opts [Array<String>] :status Status values that need to be considered for filter
# @return [Array<Pet>]
def self.find_pets_by_status(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#find_pets_by_status ..."
end
# resource path
path = "/pet/findByStatus".sub('{format}','json')
@ -114,7 +124,11 @@ module SwaggerClient
auth_names = ['petstore_auth']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
response.deserialize('Array<Pet>')
result = response.deserialize('Array<Pet>')
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}"
end
result
end
# Finds Pets by tags
@ -123,8 +137,10 @@ module SwaggerClient
# @option opts [Array<String>] :tags Tags to filter by
# @return [Array<Pet>]
def self.find_pets_by_tags(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#find_pets_by_tags ..."
end
# resource path
path = "/pet/findByTags".sub('{format}','json')
@ -152,7 +168,11 @@ module SwaggerClient
auth_names = ['petstore_auth']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
response.deserialize('Array<Pet>')
result = response.deserialize('Array<Pet>')
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}"
end
result
end
# Find pet by ID
@ -161,11 +181,13 @@ module SwaggerClient
# @param [Hash] opts the optional parameters
# @return [Pet]
def self.get_pet_by_id(pet_id, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#get_pet_by_id ..."
end
# verify the required parameter 'pet_id' is set
raise "Missing the required parameter 'pet_id' when calling get_pet_by_id" if pet_id.nil?
fail "Missing the required parameter 'pet_id' when calling get_pet_by_id" if pet_id.nil?
# resource path
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
@ -192,7 +214,11 @@ module SwaggerClient
auth_names = ['api_key', 'petstore_auth']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
response.deserialize('Pet')
result = response.deserialize('Pet')
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}"
end
result
end
# Updates a pet in the store with form data
@ -203,11 +229,13 @@ module SwaggerClient
# @option opts [String] :status Updated status of the pet
# @return [nil]
def self.update_pet_with_form(pet_id, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#update_pet_with_form ..."
end
# verify the required parameter 'pet_id' is set
raise "Missing the required parameter 'pet_id' when calling update_pet_with_form" if pet_id.nil?
fail "Missing the required parameter 'pet_id' when calling update_pet_with_form" if pet_id.nil?
# resource path
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
@ -235,7 +263,10 @@ module SwaggerClient
auth_names = ['petstore_auth']
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#update_pet_with_form"
end
nil
end
@ -246,11 +277,13 @@ module SwaggerClient
# @option opts [String] :api_key
# @return [nil]
def self.delete_pet(pet_id, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#delete_pet ..."
end
# verify the required parameter 'pet_id' is set
raise "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil?
fail "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil?
# resource path
path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
@ -277,7 +310,10 @@ module SwaggerClient
auth_names = ['petstore_auth']
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#delete_pet"
end
nil
end
@ -289,11 +325,13 @@ module SwaggerClient
# @option opts [File] :file file to upload
# @return [nil]
def self.upload_file(pet_id, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: PetApi#upload_file ..."
end
# verify the required parameter 'pet_id' is set
raise "Missing the required parameter 'pet_id' when calling upload_file" if pet_id.nil?
fail "Missing the required parameter 'pet_id' when calling upload_file" if pet_id.nil?
# resource path
path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s)
@ -321,7 +359,10 @@ module SwaggerClient
auth_names = ['petstore_auth']
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: PetApi#upload_file"
end
nil
end
end

View File

@ -1,17 +1,17 @@
require "uri"
module SwaggerClient
module Petstore
class StoreApi
basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker
# Returns pet inventories by status
# Returns a map of status codes to quantities
# @param [Hash] opts the optional parameters
# @return [Hash<String, Integer>]
def self.get_inventory(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: StoreApi#get_inventory ..."
end
# resource path
path = "/store/inventory".sub('{format}','json')
@ -38,7 +38,11 @@ module SwaggerClient
auth_names = ['api_key']
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
response.deserialize('Hash<String, Integer>')
result = response.deserialize('Hash<String, Integer>')
if Swagger.configuration.debug
Swagger.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}"
end
result
end
# Place an order for a pet
@ -47,8 +51,10 @@ module SwaggerClient
# @option opts [Order] :body order placed for purchasing the pet
# @return [Order]
def self.place_order(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: StoreApi#place_order ..."
end
# resource path
path = "/store/order".sub('{format}','json')
@ -75,7 +81,11 @@ module SwaggerClient
auth_names = []
response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
response.deserialize('Order')
result = response.deserialize('Order')
if Swagger.configuration.debug
Swagger.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}"
end
result
end
# Find purchase order by ID
@ -84,11 +94,13 @@ module SwaggerClient
# @param [Hash] opts the optional parameters
# @return [Order]
def self.get_order_by_id(order_id, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: StoreApi#get_order_by_id ..."
end
# verify the required parameter 'order_id' is set
raise "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil?
fail "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil?
# resource path
path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s)
@ -115,7 +127,11 @@ module SwaggerClient
auth_names = []
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
response.deserialize('Order')
result = response.deserialize('Order')
if Swagger.configuration.debug
Swagger.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}"
end
result
end
# Delete purchase order by ID
@ -124,11 +140,13 @@ module SwaggerClient
# @param [Hash] opts the optional parameters
# @return [nil]
def self.delete_order(order_id, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: StoreApi#delete_order ..."
end
# verify the required parameter 'order_id' is set
raise "Missing the required parameter 'order_id' when calling delete_order" if order_id.nil?
fail "Missing the required parameter 'order_id' when calling delete_order" if order_id.nil?
# resource path
path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s)
@ -154,7 +172,10 @@ module SwaggerClient
auth_names = []
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: StoreApi#delete_order"
end
nil
end
end

View File

@ -1,9 +1,7 @@
require "uri"
module SwaggerClient
module Petstore
class UserApi
basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker
# Create user
# This can only be done by the logged in user.
@ -11,8 +9,10 @@ module SwaggerClient
# @option opts [User] :body Created user object
# @return [nil]
def self.create_user(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#create_user ..."
end
# resource path
path = "/user".sub('{format}','json')
@ -38,7 +38,10 @@ module SwaggerClient
auth_names = []
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#create_user"
end
nil
end
@ -48,8 +51,10 @@ module SwaggerClient
# @option opts [Array<User>] :body List of user object
# @return [nil]
def self.create_users_with_array_input(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#create_users_with_array_input ..."
end
# resource path
path = "/user/createWithArray".sub('{format}','json')
@ -75,7 +80,10 @@ module SwaggerClient
auth_names = []
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#create_users_with_array_input"
end
nil
end
@ -85,8 +93,10 @@ module SwaggerClient
# @option opts [Array<User>] :body List of user object
# @return [nil]
def self.create_users_with_list_input(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#create_users_with_list_input ..."
end
# resource path
path = "/user/createWithList".sub('{format}','json')
@ -112,7 +122,10 @@ module SwaggerClient
auth_names = []
Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#create_users_with_list_input"
end
nil
end
@ -123,8 +136,10 @@ module SwaggerClient
# @option opts [String] :password The password for login in clear text
# @return [String]
def self.login_user(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#login_user ..."
end
# resource path
path = "/user/login".sub('{format}','json')
@ -153,7 +168,11 @@ module SwaggerClient
auth_names = []
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
response.deserialize('String')
result = response.deserialize('String')
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}"
end
result
end
# Logs out current logged in user session
@ -161,8 +180,10 @@ module SwaggerClient
# @param [Hash] opts the optional parameters
# @return [nil]
def self.logout_user(opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#logout_user ..."
end
# resource path
path = "/user/logout".sub('{format}','json')
@ -188,7 +209,10 @@ module SwaggerClient
auth_names = []
Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#logout_user"
end
nil
end
@ -198,11 +222,13 @@ module SwaggerClient
# @param [Hash] opts the optional parameters
# @return [User]
def self.get_user_by_name(username, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#get_user_by_name ..."
end
# verify the required parameter 'username' is set
raise "Missing the required parameter 'username' when calling get_user_by_name" if username.nil?
fail "Missing the required parameter 'username' when calling get_user_by_name" if username.nil?
# resource path
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
@ -229,7 +255,11 @@ module SwaggerClient
auth_names = []
response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
response.deserialize('User')
result = response.deserialize('User')
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}"
end
result
end
# Updated user
@ -239,11 +269,13 @@ module SwaggerClient
# @option opts [User] :body Updated user object
# @return [nil]
def self.update_user(username, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#update_user ..."
end
# verify the required parameter 'username' is set
raise "Missing the required parameter 'username' when calling update_user" if username.nil?
fail "Missing the required parameter 'username' when calling update_user" if username.nil?
# resource path
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
@ -269,7 +301,10 @@ module SwaggerClient
auth_names = []
Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
Swagger::Request.new(:PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#update_user"
end
nil
end
@ -279,11 +314,13 @@ module SwaggerClient
# @param [Hash] opts the optional parameters
# @return [nil]
def self.delete_user(username, opts = {})
if Swagger.configuration.debug
Swagger.logger.debug "Calling API: UserApi#delete_user ..."
end
# verify the required parameter 'username' is set
raise "Missing the required parameter 'username' when calling delete_user" if username.nil?
fail "Missing the required parameter 'username' when calling delete_user" if username.nil?
# resource path
path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s)
@ -309,7 +346,10 @@ module SwaggerClient
auth_names = []
Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
if Swagger.configuration.debug
Swagger.logger.debug "API called: UserApi#delete_user"
end
nil
end
end

View File

@ -1,4 +1,6 @@
module SwaggerClient
require 'date'
module Petstore
# base class containing fundamental method such as to_hash, build_from_hash and more
class BaseObject
@ -26,6 +28,8 @@ module SwaggerClient
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
@ -39,7 +43,7 @@ module SwaggerClient
false
end
else # model
_model = SwaggerClient.const_get(type).new
_model = Petstore.const_get(type).new
_model.build_from_hash(value)
end
end

View File

@ -1,4 +1,4 @@
module SwaggerClient
module Petstore
#
class Category < BaseObject
attr_accessor :id, :name
@ -32,13 +32,14 @@ module SwaggerClient
if attributes[:'id']
@id = attributes[:'id']
self.id = attributes[:'id']
end
if attributes[:'name']
@name = attributes[:'name']
self.name = attributes[:'name']
end
end
end
end

View File

@ -1,4 +1,4 @@
module SwaggerClient
module Petstore
#
class Order < BaseObject
attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete
@ -48,29 +48,38 @@ module SwaggerClient
if attributes[:'id']
@id = attributes[:'id']
self.id = attributes[:'id']
end
if attributes[:'petId']
@pet_id = attributes[:'petId']
self.pet_id = attributes[:'petId']
end
if attributes[:'quantity']
@quantity = attributes[:'quantity']
self.quantity = attributes[:'quantity']
end
if attributes[:'shipDate']
@ship_date = attributes[:'shipDate']
self.ship_date = attributes[:'shipDate']
end
if attributes[:'status']
@status = attributes[:'status']
self.status = attributes[:'status']
end
if attributes[:'complete']
@complete = attributes[:'complete']
self.complete = attributes[:'complete']
end
end
def status=(status)
allowed_values = ["placed", "approved", "delivered"]
if status && !allowed_values.include?(status)
fail "invalid value for 'status', must be one of #{allowed_values}"
end
@status = status
end
end
end

View File

@ -1,4 +1,4 @@
module SwaggerClient
module Petstore
#
class Pet < BaseObject
attr_accessor :id, :category, :name, :photo_urls, :tags, :status
@ -48,33 +48,42 @@ module SwaggerClient
if attributes[:'id']
@id = attributes[:'id']
self.id = attributes[:'id']
end
if attributes[:'category']
@category = attributes[:'category']
self.category = attributes[:'category']
end
if attributes[:'name']
@name = attributes[:'name']
self.name = attributes[:'name']
end
if attributes[:'photoUrls']
if (value = attributes[:'photoUrls']).is_a?(Array)
@photo_urls = value
self.photo_urls = value
end
end
if attributes[:'tags']
if (value = attributes[:'tags']).is_a?(Array)
@tags = value
self.tags = value
end
end
if attributes[:'status']
@status = attributes[:'status']
self.status = attributes[:'status']
end
end
def status=(status)
allowed_values = ["available", "pending", "sold"]
if status && !allowed_values.include?(status)
fail "invalid value for 'status', must be one of #{allowed_values}"
end
@status = status
end
end
end

View File

@ -1,4 +1,4 @@
module SwaggerClient
module Petstore
#
class Tag < BaseObject
attr_accessor :id, :name
@ -32,13 +32,14 @@ module SwaggerClient
if attributes[:'id']
@id = attributes[:'id']
self.id = attributes[:'id']
end
if attributes[:'name']
@name = attributes[:'name']
self.name = attributes[:'name']
end
end
end
end

View File

@ -1,4 +1,4 @@
module SwaggerClient
module Petstore
#
class User < BaseObject
attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status
@ -56,37 +56,38 @@ module SwaggerClient
if attributes[:'id']
@id = attributes[:'id']
self.id = attributes[:'id']
end
if attributes[:'username']
@username = attributes[:'username']
self.username = attributes[:'username']
end
if attributes[:'firstName']
@first_name = attributes[:'firstName']
self.first_name = attributes[:'firstName']
end
if attributes[:'lastName']
@last_name = attributes[:'lastName']
self.last_name = attributes[:'lastName']
end
if attributes[:'email']
@email = attributes[:'email']
self.email = attributes[:'email']
end
if attributes[:'password']
@password = attributes[:'password']
self.password = attributes[:'password']
end
if attributes[:'phone']
@phone = attributes[:'phone']
self.phone = attributes[:'phone']
end
if attributes[:'userStatus']
@user_status = attributes[:'userStatus']
self.user_status = attributes[:'userStatus']
end
end
end
end

View File

@ -1,7 +1,4 @@
require 'logger'
require 'json'
module SwaggerClient
module Petstore
module Swagger
class << self
attr_accessor :logger
@ -25,8 +22,7 @@ module SwaggerClient
def configure
yield(configuration) if block_given?
# Configure logger. Default to use Rails
self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT))
self.logger = configuration.logger
# remove :// from scheme
configuration.scheme.sub!(/:\/\//, '')
@ -41,7 +37,7 @@ module SwaggerClient
end
def authenticated?
Swagger.configuration.auth_token.present?
!Swagger.configuration.auth_token.nil?
end
def de_authenticate
@ -51,7 +47,7 @@ module SwaggerClient
def authenticate
return if Swagger.authenticated?
if Swagger.configuration.username.blank? || Swagger.configuration.password.blank?
if Swagger.configuration.username.nil? || Swagger.configuration.password.nil?
raise ApiError, "Username and password are required to authenticate."
end
@ -67,6 +63,14 @@ module SwaggerClient
response_body = request.response.body
Swagger.configuration.auth_token = response_body['token']
end
def last_response
Thread.current[:swagger_last_response]
end
def last_response=(response)
Thread.current[:swagger_last_response] = response
end
end
end
end

View File

@ -1,4 +1,4 @@
module SwaggerClient
module Petstore
module Swagger
class ApiError < StandardError
attr_reader :code, :response_headers, :response_body

View File

@ -0,0 +1,101 @@
require 'logger'
module Petstore
module Swagger
class Configuration
attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format
# Defines the username used with HTTP basic authentication.
#
# @return [String]
attr_accessor :username
# Defines the password used with HTTP basic authentication.
#
# @return [String]
attr_accessor :password
# Defines API keys used with API Key authentications.
#
# @return [Hash] key: parameter name, value: parameter value (API key)
#
# @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
# config.api_key['api_key'] = 'xxx'
attr_accessor :api_key
# Defines API key prefixes used with API Key authentications.
#
# @return [Hash] key: parameter name, value: API key prefix
#
# @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
# config.api_key_prefix['api_key'] = 'Token'
attr_accessor :api_key_prefix
# Set this to false to skip verifying SSL certificate when calling API from https server.
# Default to true.
#
# @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
#
# @return [true, false]
attr_accessor :verify_ssl
# Set this to customize the certificate file to verify the peer.
#
# @return [String] the path to the certificate file
#
# @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code:
# https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145
attr_accessor :ssl_ca_cert
# Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
# details will be logged with `logger.debug` (see the `logger` attribute).
# Default to false.
#
# @return [true, false]
attr_accessor :debug
# Defines the logger used for debugging.
# Default to `Rails.logger` (when in Rails) or logging to STDOUT.
#
# @return [#debug]
attr_accessor :logger
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Defaults go in here..
def initialize
@format = 'json'
@scheme = 'http'
@host = 'petstore.swagger.io'
@base_path = '/v2'
@user_agent = "ruby-swagger-#{Swagger::VERSION}"
@inject_format = false
@force_ending_format = false
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
'User-Agent' => @user_agent
}
# keys for API key authentication (param-name => api-key)
@api_key = {}
@api_key_prefix = {}
@verify_ssl = true
@debug = false
@logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT)
end
end
end
end

View File

@ -1,21 +1,18 @@
module SwaggerClient
require 'uri'
require 'typhoeus'
module Petstore
module Swagger
class Request
require 'uri'
require 'addressable/uri'
require 'typhoeus'
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response
# All requests must have an HTTP method and a path
# Optionals parameters are :params, :headers, :body, :format, :host
def initialize(http_method, path, attributes={})
@http_method = http_method.to_sym
def initialize(http_method, path, attributes = {})
@http_method = http_method.to_sym.downcase
@path = path
attributes.each do |name, value|
send("#{name.to_s.underscore.to_sym}=", value)
end
attributes.each { |name, value| send "#{name}=", value }
@format ||= Swagger.configuration.format
@params ||= {}
@ -27,10 +24,12 @@ module SwaggerClient
if Swagger.authenticated?
@headers.merge!({:auth_token => Swagger.configuration.auth_token})
end
update_params_for_auth!
end
# Update hearder and query params based on authentication settings.
def update_params_for_auth!
(@auth_names || []).each do |auth_name|
@ -44,30 +43,23 @@ module SwaggerClient
end
end
end
# Get API key (with prefix if set).
# @param [String] param_name the parameter name of API key auth
def get_api_key_with_prefix(param_name)
if Swagger.configuration.api_key_prefix[param_name].present?
if Swagger.configuration.api_key_prefix[param_name]
"#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}"
else
Swagger.configuration.api_key[param_name]
end
end
# Construct a base URL
# Construct the request URL.
def url(options = {})
u = Addressable::URI.new(
:scheme => Swagger.configuration.scheme,
:host => Swagger.configuration.host,
:path => self.interpreted_path,
:query => self.query_string.sub(/\?/, '')
).to_s
# Drop trailing question mark, if present
u.sub! /\?$/, ''
u
_path = self.interpreted_path
_path = "/#{_path}" unless _path.start_with?('/')
"#{Swagger.configuration.scheme}://#{Swagger.configuration.host}#{_path}"
end
# Iterate over the params hash, injecting any path values into the path string
@ -98,18 +90,6 @@ module SwaggerClient
URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/')
end
# Massage the request body into a state of readiness
# If body is a hash, camelize all keys then convert to a json string
def body=(value)
if value.is_a?(Hash)
value = value.inject({}) do |memo, (k,v)|
memo[k.to_s.camelize(:lower).to_sym] = v
memo
end
end
@body = value
end
# If body is an object, JSONify it before making the actual request.
# For form parameters, remove empty value
def outgoing_body
@ -119,93 +99,60 @@ module SwaggerClient
data.each do |key, value|
data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter
end
data
elsif @body # http body is JSON
@body.is_a?(String) ? @body : @body.to_json
data = @body.is_a?(String) ? @body : @body.to_json
else
nil
end
end
# Construct a query string from the query-string-type params
def query_string
# Iterate over all params,
# .. removing the ones that are part of the path itself.
# .. stringifying values so Addressable doesn't blow up.
query_values = {}
self.params.each_pair do |key, value|
next if self.path.include? "{#{key}}" # skip path params
next if value.blank? && value.class != FalseClass # skip empties
if Swagger.configuration.camelize_params
key = key.to_s.camelize(:lower).to_sym
end
query_values[key] = value.to_s
data = nil
end
# We don't want to end up with '?' as our query string
# if there aren't really any params
return "" if query_values.blank?
if Swagger.configuration.debug
Swagger.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n"
end
# Addressable requires query_values to be set after initialization..
qs = Addressable::URI.new
qs.query_values = query_values
qs.to_s
data
end
def make
#TODO use configuration setting to determine if debugging
#logger = Logger.new STDOUT
#logger.debug self.url
request_options = {
:method => self.http_method,
:headers => self.headers,
:params => self.params,
:ssl_verifypeer => Swagger.configuration.verify_ssl,
:headers => self.headers.stringify_keys
:cainfo => Swagger.configuration.ssl_ca_cert,
:verbose => Swagger.configuration.debug
}
response = case self.http_method.to_sym
when :get,:GET
Typhoeus::Request.get(
self.url,
request_options
)
when :post,:POST
Typhoeus::Request.post(
self.url,
request_options.merge(:body => self.outgoing_body)
)
when :patch,:PATCH
Typhoeus::Request.patch(
self.url,
request_options.merge(:body => self.outgoing_body)
)
when :put,:PUT
Typhoeus::Request.put(
self.url,
request_options.merge(:body => self.outgoing_body)
)
when :delete,:DELETE
Typhoeus::Request.delete(
self.url,
request_options.merge(:body => self.outgoing_body)
)
if [:post, :patch, :put, :delete].include?(self.http_method)
request_options.update :body => self.outgoing_body
end
Response.new(response)
end
def response
self.make
raw = Typhoeus::Request.new(self.url, request_options).run
@response = Response.new(raw)
if Swagger.configuration.debug
Swagger.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n"
end
# record as last response
Swagger.last_response = @response
unless @response.success?
fail ApiError.new(:code => @response.code,
:response_headers => @response.headers,
:response_body => @response.body),
@response.status_message
end
@response
end
def response_code_pretty
return unless @response.present?
return unless @response
@response.code.to_s
end
def response_headers_pretty
return unless @response.present?
return unless @response
# JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient
@response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
end

View File

@ -1,4 +1,4 @@
module SwaggerClient
module Petstore
module Swagger
class Response
require 'json'
@ -9,28 +9,29 @@ module SwaggerClient
def initialize(raw)
self.raw = raw
unless raw.success?
fail ApiError.new(:code => code,
:response_headers => headers,
:response_body => body),
raw.status_message
end
end
def code
raw.code
end
def status_message
raw.status_message
end
def body
raw.body
end
def success?
raw.success?
end
# Deserialize the raw response body to the given return type.
#
# @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
def deserialize(return_type)
return nil if body.blank?
return nil if body.nil? || body.empty?
# handle file downloading - save response body into a tmp file and return the File instance
return download_file if return_type == 'File'
@ -43,44 +44,52 @@ module SwaggerClient
end
begin
data = JSON.parse(body, :symbolize_names => true)
data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
rescue JSON::ParserError => e
if return_type == 'String'
return body
if %w(String Date DateTime).include?(return_type)
data = body
else
raise e
end
end
build_models data, return_type
convert_to_type data, return_type
end
# Walk through the given data and, when necessary, build model(s) from
# Hash data for array/hash values of the response.
def build_models(data, return_type)
# Convert data to the given return type.
def convert_to_type(data, return_type)
return nil if data.nil?
case return_type
when 'String', 'Integer', 'Float', 'BOOLEAN'
# primitives, return directly
data
when 'String'
data.to_s
when 'Integer'
data.to_i
when 'Float'
data.to_f
when 'BOOLEAN'
data == true
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
when 'Date'
# parse date time (expecting ISO 8601 format)
Date.parse data
when 'Object'
# generic object, return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map {|item| build_models(item, sub_type) }
data.map {|item| convert_to_type(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each {|k, v| hash[k] = build_models(v, sub_type) }
data.each {|k, v| hash[k] = convert_to_type(v, sub_type) }
end
else
# models, e.g. Pet
SwaggerClient.const_get(return_type).new.tap do |model|
Petstore.const_get(return_type).new.tap do |model|
model.build_from_hash data
end
end
@ -131,9 +140,11 @@ module SwaggerClient
end
def pretty_body
return unless body.present?
case format
when 'json' then JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>')
return unless body
if format == 'json'
JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>')
else
body
end
end

View File

@ -1,4 +1,4 @@
module SwaggerClient
module Petstore
module Swagger
VERSION = "1.0.0"
end

View File

@ -1,27 +0,0 @@
# Swagger common files
require 'swagger_client/monkey'
require 'swagger_client/swagger'
require 'swagger_client/swagger/configuration'
require 'swagger_client/swagger/api_error'
require 'swagger_client/swagger/request'
require 'swagger_client/swagger/response'
require 'swagger_client/swagger/version'
# Models
require 'swagger_client/models/base_object'
require 'swagger_client/models/user'
require 'swagger_client/models/category'
require 'swagger_client/models/pet'
require 'swagger_client/models/tag'
require 'swagger_client/models/order'
# APIs
require 'swagger_client/api/user_api'
require 'swagger_client/api/pet_api'
require 'swagger_client/api/store_api'
module SwaggerClient
# Initialize the default configuration
Swagger.configuration = Swagger::Configuration.new
Swagger.configure { |config| }
end

View File

@ -1,82 +0,0 @@
class Object
unless Object.method_defined? :blank?
def blank?
respond_to?(:empty?) ? empty? : !self
end
end
unless Object.method_defined? :present?
def present?
!blank?
end
end
end
class String
unless String.method_defined? :underscore
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
unless String.method_defined? :camelize
def camelize(first_letter_in_uppercase = true)
if first_letter_in_uppercase != :lower
self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
else
self.to_s[0].chr.downcase + camelize(self)[1..-1]
end
end
end
end
class Hash
unless Hash.method_defined? :stringify_keys
def stringify_keys
inject({}) do |options, (key, value)|
options[key.to_s] = value
options
end
end
end
unless Hash.method_defined? :stringify_keys!
def stringify_keys!
self.replace(self.stringify_keys)
end
end
unless Hash.method_defined? :symbolize_keys
def symbolize_keys
inject({}) do |options, (key, value)|
options[(key.to_sym rescue key) || key] = value
options
end
end
end
unless Hash.method_defined? :symbolize_keys!
def symbolize_keys!
self.replace(self.symbolize_keys)
end
end
unless Hash.method_defined? :symbolize_and_underscore_keys
def symbolize_and_underscore_keys
inject({}) do |options, (key, value)|
options[(key.to_s.underscore.to_sym rescue key) || key] = value
options
end
end
end
unless Hash.method_defined? :symbolize_and_underscore_keys!
def symbolize_and_underscore_keys!
self.replace(self.symbolize_and_underscore_keys)
end
end
end

View File

@ -1,46 +0,0 @@
module SwaggerClient
module Swagger
class Configuration
attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl
# Defines the temporary folder to store downloaded files
# (for API endpoints that have file response).
# Default to use `Tempfile`.
#
# @return [String]
attr_accessor :temp_folder_path
# Defines the headers to be used in HTTP requests of all API calls by default.
#
# @return [Hash]
attr_accessor :default_headers
# Defaults go in here..
def initialize
@format = 'json'
@scheme = 'http'
@host = 'petstore.swagger.io'
@base_path = '/v2'
@user_agent = "ruby-swagger-#{Swagger::VERSION}"
@inject_format = false
@force_ending_format = false
@camelize_params = true
@default_headers = {
'Content-Type' => "application/#{@format.downcase}",
'User-Agent' => @user_agent
}
# keys for API key authentication (param-name => api-key)
@api_key = {}
# api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix)
@api_key_prefix = {}
# whether to verify SSL certificate, default to true
# Note: do NOT set it to false in production code, otherwise you would
# face multiple types of cryptographic attacks
@verify_ssl = true
end
end
end
end

View File

@ -1,10 +1,10 @@
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "swagger_client/swagger/version"
require "petstore/swagger/version"
Gem::Specification.new do |s|
s.name = "swagger_client"
s.version = SwaggerClient::Swagger::VERSION
s.name = "petstore"
s.version = Petstore::Swagger::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ["Zeke Sikelianos", "Tony Tam"]
s.email = ["zeke@wordnik.com", "fehguy@gmail.com"]
@ -14,7 +14,6 @@ Gem::Specification.new do |s|
s.license = "Apache-2.0"
s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1'
s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4'
s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6'
s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0'

View File

@ -1,33 +0,0 @@
require 'spec_helper'
describe String do
it "underscores" do
"thisIsATest".underscore.should == "this_is_a_test"
end
it "camelizes" do
"camel_toe".camelize.should == "CamelToe"
end
it "camelizes with leading minisculity" do
"dromedary_larry".camelize(:lower).should == "dromedaryLarry"
end
end
describe Hash do
it "symbolizes keys" do
h = {'a' => 1, :b => 2 }
h.symbolize_keys.should be_a Hash
h.symbolize_keys.keys.should == [:a, :b]
end
it "symbolizes and underscores keys" do
h = {'assHat' => 1, :bargainBasement => 2 }
h.symbolize_and_underscore_keys.should be_a Hash
h.symbolize_and_underscore_keys.keys.should == [:ass_hat, :bargain_basement]
end
end

View File

@ -9,9 +9,9 @@ describe "Pet" do
describe "pet methods" do
it "should construct a new pet object" do
tag1 = SwaggerClient::Tag.new({'id' => 1, 'name'=> 'tag1'})
tag2 = SwaggerClient::Tag.new({'id' => 2, 'name'=> 'tag2'})
category1 = SwaggerClient::Category.new({:id => 1, :name => 'category unknown'})
tag1 = Petstore::Tag.new({'id' => 1, 'name'=> 'tag1'})
tag2 = Petstore::Tag.new({'id' => 2, 'name'=> 'tag2'})
category1 = Petstore::Category.new({:id => 1, :name => 'category unknown'})
# initalize using both string and symbol key
pet_hash = {
:id => 10002,
@ -21,7 +21,7 @@ describe "Pet" do
:category => category1,
:tags => [tag1, tag2]
}
pet = SwaggerClient::Pet.new(pet_hash)
pet = Petstore::Pet.new(pet_hash)
# test new
pet.name.should == "RUBY UNIT TESTING"
pet.status.should == "pending"
@ -31,7 +31,7 @@ describe "Pet" do
pet.category.name.should == 'category unknown'
# test build_from_hash
pet2 = SwaggerClient::Pet.new
pet2 = Petstore::Pet.new
pet2.build_from_hash(pet.to_hash)
pet.to_hash.should == pet2.to_hash
@ -42,8 +42,8 @@ describe "Pet" do
end
it "should fetch a pet object" do
pet = SwaggerClient::PetApi.get_pet_by_id(10002)
pet.should be_a(SwaggerClient::Pet)
pet = Petstore::PetApi.get_pet_by_id(10002)
pet.should be_a(Petstore::Pet)
pet.id.should == 10002
pet.name.should == "RUBY UNIT TESTING"
pet.tags[0].name.should == "tag test"
@ -52,9 +52,9 @@ describe "Pet" do
it "should not find a pet that does not exist" do
begin
SwaggerClient::PetApi.get_pet_by_id(-1)
Petstore::PetApi.get_pet_by_id(-10002)
fail 'it should raise error'
rescue SwaggerClient::Swagger::ApiError => e
rescue Petstore::Swagger::ApiError => e
e.code.should == 404
e.message.should == 'Not Found'
e.response_body.should == '{"code":1,"type":"error","message":"Pet not found"}'
@ -64,21 +64,21 @@ describe "Pet" do
end
it "should find pets by status" do
pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'available')
pets = Petstore::PetApi.find_pets_by_status(:status => 'available')
pets.length.should >= 3
pets.each do |pet|
pet.should be_a(SwaggerClient::Pet)
pet.should be_a(Petstore::Pet)
pet.status.should == 'available'
end
end
it "should not find a pet with invalid status" do
pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'invalid-status')
pets = Petstore::PetApi.find_pets_by_status(:status => 'invalid-status')
pets.length.should == 0
end
it "should find a pet by status" do
pets = SwaggerClient::PetApi.find_pets_by_status(:status => "available,sold")
pets = Petstore::PetApi.find_pets_by_status(:status => "available,sold")
pets.each do |pet|
if pet.status != 'available' && pet.status != 'sold'
raise "pet status wasn't right"
@ -87,21 +87,21 @@ describe "Pet" do
end
it "should update a pet" do
pet = SwaggerClient::Pet.new({'id' => 10002, 'status' => 'sold'})
SwaggerClient::PetApi.add_pet(:body => pet)
pet = Petstore::Pet.new({'id' => 10002, 'status' => 'sold'})
Petstore::PetApi.add_pet(:body => pet)
fetched = SwaggerClient::PetApi.get_pet_by_id(10002)
fetched = Petstore::PetApi.get_pet_by_id(10002)
fetched.id.should == 10002
fetched.status.should == 'sold'
end
it "should create a pet" do
pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING")
result = SwaggerClient::PetApi.add_pet(:body => pet)
pet = Petstore::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING")
result = Petstore::PetApi.add_pet(:body => pet)
# nothing is returned
result.should be_nil
pet = SwaggerClient::PetApi.get_pet_by_id(10002)
pet = Petstore::PetApi.get_pet_by_id(10002)
pet.id.should == 10002
pet.name.should == "RUBY UNIT TESTING"
end

View File

@ -1,9 +1,9 @@
require 'spec_helper'
describe SwaggerClient::Swagger::Request do
describe Petstore::Swagger::Request do
before(:each) do
SwaggerClient::Swagger.configure do |config|
Petstore::Swagger.configure do |config|
inject_format = true
config.api_key['api_key'] = 'special-key'
config.host = 'petstore.swagger.io'
@ -15,7 +15,7 @@ describe SwaggerClient::Swagger::Request do
@default_params = {
:params => {:foo => "1", :bar => "2"}
}
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params)
@request = Petstore::Swagger::Request.new(@default_http_method, @default_path, @default_params)
end
describe "initialization" do
@ -29,8 +29,8 @@ describe SwaggerClient::Swagger::Request do
end
it "allows params to be nil" do
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, :params => nil)
@request.query_string.should == ""
@request = Petstore::Swagger::Request.new(@default_http_method, @default_path, :params => nil)
@request.params.should == {}
end
end
@ -51,26 +51,8 @@ describe SwaggerClient::Swagger::Request do
describe "url" do
it "constructs a query string" do
@request.query_string.should == "?bar=2&foo=1"
end
it "constructs a full url" do
@request.url.should == "http://petstore.swagger.io/v2/pet.json/fancy?bar=2&foo=1"
end
end
describe "body" do
it "camelCases parameters" do
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({
:body => {
:bad_dog => 'bud',
:goodDog => "dud"
}
}))
@request.body.keys.should == [:badDog, :goodDog]
@request.url.should == "http://petstore.swagger.io/v2/pet.json/fancy"
end
end
@ -78,7 +60,7 @@ describe SwaggerClient::Swagger::Request do
describe "path" do
it "accounts for a total absence of format in the path string" do
@request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({
@request = Petstore::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({
:format => "xml",
:params => {
}
@ -87,7 +69,7 @@ describe SwaggerClient::Swagger::Request do
end
it "does string substitution (format) on path params" do
@request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({
@request = Petstore::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({
:format => "xml",
:params => {
}
@ -95,38 +77,8 @@ describe SwaggerClient::Swagger::Request do
@request.url.should == "http://petstore.swagger.io/v2/word.xml/cat/entries"
end
it "leaves path-bound params out of the query string" do
@request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({
:params => {
:word => "cat",
:limit => 20
}
}))
@request.query_string.should == "?limit=20"
end
it "returns a question-mark free (blank) query string if no query params are present" do
@request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({
:params => {
:word => "cat",
}
}))
@request.query_string.should == ""
end
it "removes blank params" do
@request = SwaggerClient::Swagger::Request.new(:get, "words/fancy", @default_params.merge({
:params => {
:word => "dog",
:limit => "",
:foo => "criminy"
}
}))
@request.query_string.should == "?foo=criminy&word=dog"
end
it "URI encodes the path" do
@request = SwaggerClient::Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({
@request = Petstore::Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({
:params => {
:word => "bill gates"
}
@ -134,39 +86,11 @@ describe SwaggerClient::Swagger::Request do
@request.url.should =~ /word.json\/bill\%20gates\/definitions/
end
it "converts numeric params to strings" do
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({
:params => {
:limit => 100
}
}))
@request.interpreted_path.should_not be_nil
@request.query_string.should =~ /\?limit=100/
@request.url.should =~ /\?limit=100/
end
it "camelCases parameters" do
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({
:params => {
:bad_dog => 'bud',
:goodDog => "dud"
}
}))
@request.query_string.should == "?badDog=bud&goodDog=dud"
end
it "converts boolean values to their string representation" do
params = {:stringy => "fish", :truthy => true, :falsey => false}
@request = SwaggerClient::Swagger::Request.new(:get, 'fakeMethod', :params => params)
@request.query_string.should == "?falsey=false&stringy=fish&truthy=true"
end
end
describe "#update_params_for_auth!" do
it "sets header api-key parameter with prefix" do
SwaggerClient::Swagger.configure do |config|
Petstore::Swagger.configure do |config|
inject_format = true
config.api_key_prefix['api_key'] = 'PREFIX'
end
@ -176,7 +100,7 @@ describe SwaggerClient::Swagger::Request do
end
it "sets header api-key parameter without prefix" do
SwaggerClient::Swagger.configure do |config|
Petstore::Swagger.configure do |config|
inject_format = true
config.api_key_prefix['api_key'] = nil
end

View File

@ -1,6 +1,6 @@
require 'spec_helper'
describe SwaggerClient::Swagger::Response do
describe Petstore::Swagger::Response do
before do
configure_swagger
@ -12,7 +12,7 @@ describe SwaggerClient::Swagger::Response do
@raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002")
end
@response = SwaggerClient::Swagger::Response.new(@raw)
@response = Petstore::Swagger::Response.new(@raw)
end
describe "initialization" do
@ -43,7 +43,7 @@ describe SwaggerClient::Swagger::Response do
@raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002",
:headers => {'Accept'=> "application/xml"})
end
@response = SwaggerClient::Swagger::Response.new(@raw)
@response = Petstore::Swagger::Response.new(@raw)
@response.format.should == 'xml'
@response.xml?.should == true
end
@ -74,7 +74,7 @@ describe SwaggerClient::Swagger::Response do
data.should be_a(Hash)
data.keys.should == [:pet]
pet = data[:pet]
pet.should be_a(SwaggerClient::Pet)
pet.should be_a(Petstore::Pet)
pet.id.should == 10002
end
end

View File

@ -1,6 +1,6 @@
require 'rubygems'
require 'bundler/setup'
require 'swagger_client'
require 'petstore'
require 'vcr'
require 'typhoeus'
require 'json'
@ -37,7 +37,7 @@ end
#end
def configure_swagger
SwaggerClient::Swagger.configure do |config|
Petstore::Swagger.configure do |config|
config.api_key['api_key'] = 'special-key'
config.host = 'petstore.swagger.io'
config.base_path = '/v2'
@ -47,25 +47,25 @@ end
# always delete and then re-create the pet object with 10002
def prepare_pet
# remove the pet
SwaggerClient::PetApi.delete_pet(10002)
Petstore::PetApi.delete_pet(10002)
# recreate the pet
category = SwaggerClient::Category.new('id' => 20002, 'name' => 'category test')
tag = SwaggerClient::Tag.new('id' => 30002, 'name' => 'tag test')
pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url',
category = Petstore::Category.new('id' => 20002, 'name' => 'category test')
tag = Petstore::Tag.new('id' => 30002, 'name' => 'tag test')
pet = Petstore::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url',
'category' => category, 'tags' => [tag], 'status' => 'pending')
SwaggerClient::PetApi.add_pet(:'body'=> pet)
Petstore::PetApi.add_pet(:'body'=> pet)
end
# always delete and then re-create the store order
def prepare_store
order = SwaggerClient::Order.new("id" => 10002,
order = Petstore::Order.new("id" => 10002,
"petId" => 10002,
"quantity" => 789,
"shipDate" => "2015-04-06T23:42:01.678Z",
"status" => "placed",
"complete" => false)
SwaggerClient::StoreApi.place_order(:body => order)
Petstore::StoreApi.place_order(:body => order)
end
configure_swagger

View File

@ -7,12 +7,12 @@ describe "Store" do
end
it "should fetch an order" do
item = SwaggerClient::StoreApi.get_order_by_id(10002)
item = Petstore::StoreApi.get_order_by_id(10002)
item.id.should == 10002
end
it "should featch the inventory" do
result = SwaggerClient::StoreApi.get_inventory
result = Petstore::StoreApi.get_inventory
result.should be_a(Hash)
result.should_not be_empty
result.each do |k, v|

View File

@ -1,56 +1,56 @@
# require 'spec_helper'
require File.dirname(__FILE__) + '/spec_helper'
describe SwaggerClient::Swagger do
describe Petstore::Swagger do
before(:each) do
configure_swagger
end
after(:each) do
end
context 'initialization' do
context 'URL stuff' do
context 'host' do
it 'removes http from host' do
SwaggerClient::Swagger.configure {|c| c.host = 'http://example.com' }
SwaggerClient::Swagger.configuration.host.should == 'example.com'
Petstore::Swagger.configure {|c| c.host = 'http://example.com' }
Petstore::Swagger.configuration.host.should == 'example.com'
end
it 'removes https from host' do
SwaggerClient::Swagger.configure {|c| c.host = 'https://wookiee.com' }
SwaggerClient::Swagger.configuration.host.should == 'wookiee.com'
Petstore::Swagger.configure {|c| c.host = 'https://wookiee.com' }
Petstore::Swagger.configuration.host.should == 'wookiee.com'
end
it 'removes trailing path from host' do
SwaggerClient::Swagger.configure {|c| c.host = 'hobo.com/v4' }
SwaggerClient::Swagger.configuration.host.should == 'hobo.com'
Petstore::Swagger.configure {|c| c.host = 'hobo.com/v4' }
Petstore::Swagger.configuration.host.should == 'hobo.com'
end
end
context 'base_path' do
it "prepends a slash to base_path" do
SwaggerClient::Swagger.configure {|c| c.base_path = 'v4/dog' }
SwaggerClient::Swagger.configuration.base_path.should == '/v4/dog'
Petstore::Swagger.configure {|c| c.base_path = 'v4/dog' }
Petstore::Swagger.configuration.base_path.should == '/v4/dog'
end
it "doesn't prepend a slash if one is already there" do
SwaggerClient::Swagger.configure {|c| c.base_path = '/v4/dog' }
SwaggerClient::Swagger.configuration.base_path.should == '/v4/dog'
Petstore::Swagger.configure {|c| c.base_path = '/v4/dog' }
Petstore::Swagger.configuration.base_path.should == '/v4/dog'
end
it "ends up as a blank string if nil" do
SwaggerClient::Swagger.configure {|c| c.base_path = nil }
SwaggerClient::Swagger.configuration.base_path.should == ''
Petstore::Swagger.configure {|c| c.base_path = nil }
Petstore::Swagger.configuration.base_path.should == ''
end
end
end
end
end