fix rspec, update ruby client default configuration

This commit is contained in:
William Cheng 2015-03-31 01:28:33 +08:00
parent a4ce6d7074
commit 0ee39c67fe
14 changed files with 89 additions and 359 deletions

View File

@ -9,10 +9,10 @@ module Swagger
def initialize
@format = 'json'
@scheme = 'http'
@host = 'api.wordnik.com'
@base_path = '/v4'
@host = 'petstore.swagger.io'
@base_path = '/v2'
@user_agent = "ruby-swagger-#{Swagger::VERSION}"
@inject_format = true
@inject_format = false
@force_ending_format = false
@camelize_params = true
end

View File

@ -157,8 +157,9 @@ module Swagger
end
def make
logger = Logger.new STDOUT
logger.debug self.url
#TODO use configuration setting to determine if debugging
#logger = Logger.new STDOUT
#logger.debug self.url
response = case self.http_method.to_sym
when :get,:GET
Typhoeus::Request.get(

View File

@ -9,35 +9,43 @@ PATH
GEM
remote: http://rubygems.org/
specs:
ZenTest (4.7.0)
addressable (2.2.8)
ZenTest (4.11.0)
addressable (2.3.8)
autotest (4.4.6)
ZenTest (>= 4.4.1)
autotest-fsevent (0.2.8)
autotest-fsevent (0.2.10)
sys-uname
autotest-growl (0.2.16)
autotest-rails-pure (4.1.2)
crack (0.3.1)
diff-lcs (1.1.3)
ffi (1.0.11)
json (1.7.0)
mime-types (1.18)
rspec (2.9.0)
rspec-core (~> 2.9.0)
rspec-expectations (~> 2.9.0)
rspec-mocks (~> 2.9.0)
rspec-core (2.9.0)
rspec-expectations (2.9.1)
diff-lcs (~> 1.1.3)
rspec-mocks (2.9.0)
sys-uname (0.9.0)
crack (0.4.2)
safe_yaml (~> 1.0.0)
diff-lcs (1.2.5)
ethon (0.7.3)
ffi (>= 1.3.0)
ffi (1.9.8)
json (1.8.2)
rspec (3.2.0)
rspec-core (~> 3.2.0)
rspec-expectations (~> 3.2.0)
rspec-mocks (~> 3.2.0)
rspec-core (3.2.2)
rspec-support (~> 3.2.0)
rspec-expectations (3.2.0)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.2.0)
rspec-mocks (3.2.1)
diff-lcs (>= 1.2.0, < 2.0)
rspec-support (~> 3.2.0)
rspec-support (3.2.2)
safe_yaml (1.0.4)
sys-uname (0.9.2)
ffi (>= 1.0.0)
typhoeus (0.3.3)
mime-types
vcr (2.1.1)
webmock (1.8.6)
addressable (>= 2.2.7)
crack (>= 0.1.7)
typhoeus (0.7.1)
ethon (>= 0.7.1)
vcr (2.9.3)
webmock (1.21.0)
addressable (>= 2.3.6)
crack (>= 0.3.2)
PLATFORMS
ruby

View File

@ -9,10 +9,10 @@ module Swagger
def initialize
@format = 'json'
@scheme = 'http'
@host = 'api.wordnik.com'
@base_path = '/v4'
@host = 'petstore.swagger.io'
@base_path = '/v2'
@user_agent = "ruby-swagger-#{Swagger::VERSION}"
@inject_format = true
@inject_format = false
@force_ending_format = false
@camelize_params = true
end

View File

@ -157,8 +157,9 @@ module Swagger
end
def make
logger = Logger.new STDOUT
logger.debug self.url
#TODO use configuration setting to determine if debugging
#logger = Logger.new STDOUT
#logger.debug self.url
response = case self.http_method.to_sym
when :get,:GET
Typhoeus::Request.get(

View File

@ -17,7 +17,6 @@ class Pet
def initialize(attributes = {})
return if attributes.empty?
# Morph attribute keys into undescored rubyish style
if self.class.attribute_map[:"id"]
@id = attributes["id"]
end

View File

@ -4,30 +4,30 @@ describe "Pet" do
before do
Swagger.configure do |config|
config.api_key = 'special-key'
config.host = 'petstore.swagger.wordnik.com'
config.base_path = '/api'
config.host = 'petstore.swagger.io'
config.base_path = '/v2'
end
end
describe "pet methods" do
it "should fetch a pet object" do
pet = Pet_api.get_pet_by_id(1)
pet.id.should == 1
pet.name.should == "Cat 1"
pet = PetApi.getPetById(5)
pet.id.should == 5
pet.name.should == "Dog 2"
end
it "should find pets by status" do
pets = Pet_api.find_pets_by_status('available')
pets = PetApi.findPetsByStatus('available')
pets.length.should >= 3
end
it "should not find a pet with invalid status" do
pets = Pet_api.find_pets_by_status('dead')
pets = PetApi.findPetsByStatus('dead')
pets.length.should == 0
end
it "should find a pet by status" do
pets = Pet_api.find_pets_by_status("available,sold")
pets = PetApi.findPetsByStatus("available,sold")
pets.map {|pet|
if(pet.status != 'available' && pet.status != 'sold')
raise "pet status wasn't right"
@ -36,19 +36,19 @@ describe "Pet" do
end
it "should update a pet" do
pet = Pet.new({:id => 99, :name => 'programmer', :status => 'coding'})
Pet_api.add_pet(pet)
pet = Pet.new({'id' => 99, 'name' => 'programmer', 'status' => 'coding'})
PetApi.addPet(pet)
fetched = Pet_api.get_pet_by_id(99)
fetched = PetApi.getPetById(99)
fetched.id.should == 99
end
it "should create a pet" do
pet = Pet.new({:id => 100, :name => "Gorilla"})
raise pet.inspect
Pet_api.add_pet(pet)
pet = Pet.new('id' => 100, 'name' => "Gorilla")
#raise pet.inspect
PetApi.addPet(pet)
pet = Pet_api.get_pet_by_id(100)
pet = PetApi.getPetById(100)
pet.id.should == 100
end
end
@ -58,13 +58,13 @@ describe "Store" do
before do
Swagger.configure do |config|
config.api_key = 'special-key'
config.host = 'petstore.swagger.wordnik.com'
config.base_path = '/api'
config.host = 'petstore.swagger.io'
config.base_path = '/v2'
end
end
it "should fetch an order" do
item = Store_api.get_order_by_id(1)
item = StoreApi.getOrderById(1)
item.id.should == 1
end
end
end

View File

@ -2,9 +2,16 @@ require 'spec_helper'
describe Swagger::Request do
before(:each) do
before(:each) do
Swagger.configure do |config|
inject_format = true
config.api_key = 'special-key'
config.host = 'petstore.swagger.io'
config.base_path = '/v2'
end
@default_http_method = :get
@default_path = "pet/fancy"
@default_path = "pet.{format}/fancy"
@default_params = {
:params => {:foo => "1", :bar => "2"}
}
@ -44,7 +51,7 @@ describe Swagger::Request do
end
it "constructs a full url" do
@request.url.should == "http://petstore.swagger.wordnik.com/api/pet.json/fancy?bar=2&foo=1"
@request.url.should == "http://petstore.swagger.io/v2/pet.json/fancy?bar=2&foo=1"
end
end
@ -66,13 +73,13 @@ describe Swagger::Request do
describe "path" do
it "accounts for a total absence of format in the path string" do
@request = Swagger::Request.new(:get, "/word/{word}/entries", @default_params.merge({
@request = Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({
:format => "xml",
:params => {
:word => "cat"
}
}))
@request.url.should == "http://petstore.swagger.wordnik.com/api/word.xml/cat/entries"
@request.url.should == "http://petstore.swagger.io/v2/word.xml/cat/entries"
end
it "does string substitution on path params" do
@ -82,7 +89,7 @@ describe Swagger::Request do
:word => "cat"
}
}))
@request.url.should == "http://petstore.swagger.wordnik.com/api/word.xml/cat/entries"
@request.url.should == "http://petstore.swagger.io/v2/word.xml/cat/entries"
end
it "leaves path-bound params out of the query string" do
@ -193,4 +200,4 @@ describe Swagger::Request do
end
end
end

View File

@ -5,7 +5,8 @@ describe Swagger::Response do
before(:each) do
VCR.use_cassette('pet_resource', :record => :new_episodes) do
@raw = Typhoeus::Request.get("http://petstore.swagger.wordnik.com/api/pet.json")
#@raw = Typhoeus::Request.get("http://petstore.swagger.wordnik.com/api/pet.json")
@raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/5")
end
@response = Swagger::Response.new(@raw)
@ -14,7 +15,7 @@ describe Swagger::Response do
describe "initialization" do
it "sets body" do
@response.body.class.should == Hash
@response.body.has_key?('apis').should == true
@response.body.has_key?('name').should == true
end
it "sets code" do
@ -35,7 +36,8 @@ describe Swagger::Response do
it "recognizes xml" do
VCR.use_cassette('xml_response_request', :record => :new_episodes) do
@raw = Typhoeus::Request.get("http://petstore.swagger.wordnik.com/api/pet.xml")
@raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/5",
:headers => {'Accept'=> "application/xml"})
end
@response = Swagger::Response.new(@raw)
@response.format.should == 'xml'
@ -56,4 +58,4 @@ describe Swagger::Response do
end
end
end

View File

@ -14,8 +14,15 @@ Dir[File.join(File.dirname(__FILE__), "../resources/*.rb")].each {|file| require
RSpec.configure do |config|
# some (optional) config here
config.expect_with :rspec do |c|
c.syntax = :should
end
config.mock_with :rspec do |c|
c.syntax = :should
end
end
WebMock.allow_net_connect! if defined? WebMock
def help

View File

@ -1,22 +0,0 @@
module Swagger
class Configuration
require 'swagger/version'
attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params
# Defaults go in here..
def initialize
@format = 'json'
@scheme = 'http'
@host = 'api.wordnik.com'
@base_path = '/v4'
@user_agent = "ruby-#{Swagger::VERSION}"
@inject_format = true
@force_ending_format = false
@camelize_params = true
end
end
end

View File

@ -1,199 +0,0 @@
module Swagger
class Request
require 'uri'
require 'addressable/uri'
require 'typhoeus'
require "swagger/version"
attr_accessor :host, :path, :format, :params, :body, :http_method, :headers
# All requests must have an HTTP method and a path
# Optionals parameters are :params, :headers, :body, :format, :host
#
def initialize(http_method, path, attributes={})
attributes[:format] ||= Swagger.configuration.format
attributes[:params] ||= {}
# Set default headers
default_headers = {
'Content-Type' => "application/#{attributes[:format].downcase}",
:api_key => Swagger.configuration.api_key
}
# api_key from headers hash trumps the default, even if its value is blank
if attributes[:headers].present? && attributes[:headers].has_key?(:api_key)
default_headers.delete(:api_key)
end
# api_key from params hash trumps all others (headers and default_headers)
if attributes[:params].present? && attributes[:params].has_key?(:api_key)
default_headers.delete(:api_key)
attributes[:headers].delete(:api_key) if attributes[:headers].present?
end
# Merge argument headers into defaults
attributes[:headers] = default_headers.merge(attributes[:headers] || {})
# Stick in the auth token if there is one
if Swagger.authenticated?
attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token})
end
self.http_method = http_method.to_sym
self.path = path
attributes.each do |name, value|
send("#{name.to_s.underscore.to_sym}=", value)
end
end
# Construct a base 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! /\?$/, ''
# Obfuscate API key?
u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated]
u
end
# Iterate over the params hash, injecting any path values into the path string
#
# e.g. /word.{format}/{word}/entries => /word.json/cat/entries
def interpreted_path
p = self.path.dup
# Fill in the path params
self.params.each_pair do |key, value|
p = p.gsub("{#{key}}", value.to_s)
end
# Stick a .{format} placeholder into the path if there isn't
# one already or an actual format like json or xml
# e.g. /words/blah => /words.{format}/blah
if Swagger.configuration.inject_format
unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
p = p.sub(/^(\/?\w+)/, "\\1.#{format}")
end
end
# Stick a .{format} placeholder on the end of the path if there isn't
# one already or an actual format like json or xml
# e.g. /words/blah => /words/blah.{format}
if Swagger.configuration.force_ending_format
unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s }
p = "#{p}.#{format}"
end
end
p = p.sub("{format}", self.format.to_s)
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.
#
def outgoing_body
body.is_a?(String) ? body : body.to_json
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 unless key.to_sym == :api_key # api_key is not a camelCased param
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
logger = Logger.new STDOUT
logger.debug self.url
response = case self.http_method.to_sym
when :get,:GET
Typhoeus::Request.get(
self.url,
:headers => self.headers.stringify_keys,
)
when :post,:POST
Typhoeus::Request.post(
self.url,
:body => self.outgoing_body,
:headers => self.headers.stringify_keys,
)
when :put,:PUT
Typhoeus::Request.put(
self.url,
:body => self.outgoing_body,
:headers => self.headers.stringify_keys,
)
when :delete,:DELETE
Typhoeus::Request.delete(
self.url,
:body => self.outgoing_body,
:headers => self.headers.stringify_keys,
)
end
Response.new(response)
end
def response
self.make
end
def response_code_pretty
return unless @response.present?
@response.code.to_s
end
def response_headers_pretty
return unless @response.present?
# JSON.pretty_generate(@response.headers).gsub(/\n/, '<br/>') # <- This was for RestClient
@response.headers.gsub(/\n/, '<br/>') # <- This is for Typhoeus
end
end
end

View File

@ -1,70 +0,0 @@
module Swagger
class Response
require 'json'
attr_accessor :raw
def initialize(raw)
self.raw = raw
case self.code
when 500..510 then raise(ServerError, self.error_message)
when 299..426 then raise(ClientError, self.error_message)
end
end
def code
raw.code
end
# Account for error messages that take different forms...
def error_message
body['message']
rescue
body
end
# If body is JSON, parse it
# Otherwise return raw string
def body
JSON.parse raw.body
rescue
raw.body
end
# `headers_hash` is a Typhoeus-specific extension of Hash,
# so simplify it back into a regular old Hash.
def headers
h = {}
raw.headers_hash.each {|k,v| h[k] = v }
h
end
# Extract the response format from the header hash
# e.g. {'Content-Type' => 'application/json'}
def format
headers['Content-Type'].split("/").last.downcase
end
def json?
format == 'json'
end
def xml?
format == 'xml'
end
def pretty_body
return unless body.present?
case format
when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>')
end
end
def pretty_headers
JSON.pretty_generate(headers).gsub(/\n/, '<br/>')
end
end
end

View File

@ -1,4 +0,0 @@
module Swagger
VERSION = "4.06.08"
end