Rebuild Ruby petstore client

This commit is contained in:
xhh 2015-06-26 16:37:58 +08:00
parent 8c10e4f2b0
commit 2d3d35cfd7
14 changed files with 33 additions and 301 deletions

View File

@ -120,6 +120,7 @@ module {{moduleName}}
request_options = { request_options = {
:method => self.http_method, :method => self.http_method,
:headers => self.headers, :headers => self.headers,
:params => self.params,
:ssl_verifypeer => Swagger.configuration.verify_ssl, :ssl_verifypeer => Swagger.configuration.verify_ssl,
:cainfo => Swagger.configuration.ssl_ca_cert, :cainfo => Swagger.configuration.ssl_ca_cert,
:verbose => Swagger.configuration.debug :verbose => Swagger.configuration.debug

View File

@ -2,7 +2,6 @@ PATH
remote: . remote: .
specs: specs:
swagger_client (1.0.0) swagger_client (1.0.0)
addressable (~> 2.2, >= 2.2.4)
json (~> 1.4, >= 1.4.6) json (~> 1.4, >= 1.4.6)
typhoeus (~> 0.2, >= 0.2.1) typhoeus (~> 0.2, >= 0.2.1)

View File

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

View File

@ -2,8 +2,6 @@ require "uri"
module SwaggerClient module SwaggerClient
class PetApi class PetApi
basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker
# Update an existing pet # Update an existing pet
# #

View File

@ -2,8 +2,6 @@ require "uri"
module SwaggerClient module SwaggerClient
class StoreApi class StoreApi
basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker
# Returns pet inventories by status # Returns pet inventories by status
# Returns a map of status codes to quantities # Returns a map of status codes to quantities

View File

@ -2,8 +2,6 @@ require "uri"
module SwaggerClient module SwaggerClient
class UserApi class UserApi
basePath = "http://petstore.swagger.io/v2"
# apiInvoker = APIInvoker
# Create user # Create user
# This can only be done by the logged in user. # This can only be done by the logged in user.

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

@ -37,7 +37,7 @@ module SwaggerClient
end end
def authenticated? def authenticated?
Swagger.configuration.auth_token.present? !Swagger.configuration.auth_token.nil?
end end
def de_authenticate def de_authenticate
@ -47,7 +47,7 @@ module SwaggerClient
def authenticate def authenticate
return if Swagger.authenticated? 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." raise ApiError, "Username and password are required to authenticate."
end end

View File

@ -3,7 +3,7 @@ require 'logger'
module SwaggerClient module SwaggerClient
module Swagger module Swagger
class Configuration class Configuration
attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format, :camelize_params attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format
# Defines the username used with HTTP basic authentication. # Defines the username used with HTTP basic authentication.
# #
@ -69,7 +69,6 @@ module SwaggerClient
@user_agent = "ruby-swagger-#{Swagger::VERSION}" @user_agent = "ruby-swagger-#{Swagger::VERSION}"
@inject_format = false @inject_format = false
@force_ending_format = false @force_ending_format = false
@camelize_params = true
@api_key = {} @api_key = {}
@api_key_prefix = {} @api_key_prefix = {}

View File

@ -1,15 +1,14 @@
require 'uri'
require 'typhoeus'
module SwaggerClient module SwaggerClient
module Swagger module Swagger
class Request class Request
require 'uri'
require 'addressable/uri'
require 'typhoeus'
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response 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 # All requests must have an HTTP method and a path
# Optionals parameters are :params, :headers, :body, :format, :host # Optionals parameters are :params, :headers, :body, :format, :host
def initialize(http_method, path, attributes={}) def initialize(http_method, path, attributes = {})
attributes[:format] ||= Swagger.configuration.format attributes[:format] ||= Swagger.configuration.format
attributes[:params] ||= {} attributes[:params] ||= {}
@ -27,11 +26,10 @@ module SwaggerClient
attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
end end
self.http_method = http_method.to_sym self.http_method = http_method.to_sym.downcase
self.path = path self.path = path
attributes.each do |name, value|
send("#{name.to_s.underscore.to_sym}=", value) attributes.each { |name, value| send "#{name}=", value }
end
update_params_for_auth! update_params_for_auth!
end end
@ -53,26 +51,18 @@ module SwaggerClient
# Get API key (with prefix if set). # Get API key (with prefix if set).
# @param [String] param_name the parameter name of API key auth # @param [String] param_name the parameter name of API key auth
def get_api_key_with_prefix(param_name) 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]}" "#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}"
else else
Swagger.configuration.api_key[param_name] Swagger.configuration.api_key[param_name]
end end
end end
# Construct a base URL # Construct the request URL.
def url(options = {}) def url(options = {})
u = Addressable::URI.new( _path = self.interpreted_path
:scheme => Swagger.configuration.scheme, _path = "/#{_path}" unless _path.start_with?('/')
:host => Swagger.configuration.host, "#{Swagger.configuration.scheme}://#{Swagger.configuration.host}#{_path}"
:path => self.interpreted_path,
:query => self.query_string.sub(/\?/, '')
).to_s
# Drop trailing question mark, if present
u.sub! /\?$/, ''
u
end end
# Iterate over the params hash, injecting any path values into the path string # Iterate over the params hash, injecting any path values into the path string
@ -103,18 +93,6 @@ module SwaggerClient
URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/')
end 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. # If body is an object, JSONify it before making the actual request.
# For form parameters, remove empty value # For form parameters, remove empty value
def outgoing_body def outgoing_body
@ -137,70 +115,21 @@ module SwaggerClient
data data
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
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?
# Addressable requires query_values to be set after initialization..
qs = Addressable::URI.new
qs.query_values = query_values
qs.to_s
end
def make def make
request_options = { request_options = {
:method => self.http_method,
:headers => self.headers,
:params => self.params,
:ssl_verifypeer => Swagger.configuration.verify_ssl, :ssl_verifypeer => Swagger.configuration.verify_ssl,
:cainfo => Swagger.configuration.ssl_ca_cert, :cainfo => Swagger.configuration.ssl_ca_cert,
:headers => self.headers.stringify_keys,
:verbose => Swagger.configuration.debug :verbose => Swagger.configuration.debug
} }
raw = case self.http_method.to_sym
when :get,:GET
Typhoeus::Request.get(
self.url,
request_options
)
when :post,:POST if [:post, :patch, :put, :delete].include?(self.http_method)
Typhoeus::Request.post( request_options.update :body => self.outgoing_body
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)
)
end end
raw = Typhoeus::Request.new(self.url, request_options).run
@response = Response.new(raw) @response = Response.new(raw)
if Swagger.configuration.debug if Swagger.configuration.debug
@ -216,16 +145,17 @@ module SwaggerClient
:response_body => @response.body), :response_body => @response.body),
@response.status_message @response.status_message
end end
@response @response
end end
def response_code_pretty def response_code_pretty
return unless @response.present? return unless @response
@response.code.to_s @response.code.to_s
end end
def response_headers_pretty def response_headers_pretty
return unless @response.present? return unless @response
# JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient # JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient
@response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus @response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
end end

View File

@ -30,7 +30,7 @@ module SwaggerClient
# #
# @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
def deserialize(return_type) def deserialize(return_type)
return nil if body.blank? return nil if body.nil? || body.empty?
# ensuring a default content type # ensuring a default content type
content_type = raw.headers_hash['Content-Type'] || 'application/json' content_type = raw.headers_hash['Content-Type'] || 'application/json'
@ -106,9 +106,11 @@ module SwaggerClient
end end
def pretty_body def pretty_body
return unless body.present? return unless body
case format if format == 'json'
when 'json' then JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>') JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>')
else
body
end end
end end

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

@ -25,7 +25,7 @@ describe SwaggerClient::Swagger::Request do
it "allows params to be nil" do it "allows params to be nil" do
@request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, :params => nil) @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, :params => nil)
@request.query_string.should == "" @request.params.should == {}
end end
end end
@ -46,26 +46,8 @@ describe SwaggerClient::Swagger::Request do
describe "url" 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 it "constructs a full url" do
@request.url.should == "http://petstore.swagger.io/v2/pet.json/fancy?bar=2&foo=1" @request.url.should == "http://petstore.swagger.io/v2/pet.json/fancy"
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]
end end
end end
@ -90,36 +72,6 @@ describe SwaggerClient::Swagger::Request do
@request.url.should == "http://petstore.swagger.io/v2/word.xml/cat/entries" @request.url.should == "http://petstore.swagger.io/v2/word.xml/cat/entries"
end 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 it "URI encodes the path" do
@request = SwaggerClient::Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({ @request = SwaggerClient::Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({
:params => { :params => {
@ -129,34 +81,6 @@ describe SwaggerClient::Swagger::Request do
@request.url.should =~ /word.json\/bill\%20gates\/definitions/ @request.url.should =~ /word.json\/bill\%20gates\/definitions/
end 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 end
describe "#update_params_for_auth!" do describe "#update_params_for_auth!" do

View File

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