1
0
Fork 0
mirror of https://github.com/jnunemaker/httparty synced 2023-03-27 23:23:07 -04:00

Merge pull request #1 from mikeastock/mas/rspec_3_upgrade

RSpec 3 Upgrade
This commit is contained in:
Michael Stock 2014-12-06 17:38:31 -08:00
commit b00e26e293
16 changed files with 709 additions and 581 deletions

View file

@ -4,7 +4,7 @@ gemspec
gem 'rake'
gem 'cucumber', '~> 0.7'
gem 'fakeweb', '~> 1.3'
gem 'rspec', '~> 1.3'
gem 'rspec', '~> 3.1'
gem 'mongrel', '1.2.0.pre2'
group :development do
@ -15,4 +15,4 @@ end
group :test do
gem 'simplecov', require: false
end
end

View file

@ -1,8 +1,7 @@
require 'spec/rake/spectask'
Spec::Rake::SpecTask.new(:spec) do |spec|
spec.ruby_opts << '-rubygems'
spec.libs << 'lib' << 'spec'
spec.spec_files = FileList['spec/**/*_spec.rb']
begin
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new(:spec)
rescue LoadError
end
require 'cucumber/rake/task'

View file

@ -1,6 +1,6 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
describe HTTParty::ConnectionAdapter do
RSpec.describe HTTParty::ConnectionAdapter do
describe "initialization" do
let(:uri) { URI 'http://www.google.com' }
@ -18,7 +18,7 @@ describe HTTParty::ConnectionAdapter do
it "sets the uri" do
adapter = HTTParty::ConnectionAdapter.new(uri)
adapter.uri.should be uri
expect(adapter.uri).to be uri
end
it "also accepts an optional options hash" do
@ -28,22 +28,22 @@ describe HTTParty::ConnectionAdapter do
it "sets the options" do
options = {foo: :bar}
adapter = HTTParty::ConnectionAdapter.new(uri, options)
adapter.options.should be options
expect(adapter.options).to be options
end
end
describe ".call" do
it "generates an HTTParty::ConnectionAdapter instance with the given uri and options" do
HTTParty::ConnectionAdapter.should_receive(:new).with(@uri, @options).and_return(stub(connection: nil))
expect(HTTParty::ConnectionAdapter).to receive(:new).with(@uri, @options).and_return(double(connection: nil))
HTTParty::ConnectionAdapter.call(@uri, @options)
end
it "calls #connection on the connection adapter" do
adapter = mock('Adapter')
connection = mock('Connection')
adapter.should_receive(:connection).and_return(connection)
HTTParty::ConnectionAdapter.stub(new: adapter)
HTTParty::ConnectionAdapter.call(@uri, @options).should be connection
adapter = double('Adapter')
connection = double('Connection')
expect(adapter).to receive(:connection).and_return(connection)
allow(HTTParty::ConnectionAdapter).to receive_messages(new: adapter)
expect(HTTParty::ConnectionAdapter.call(@uri, @options)).to be connection
end
end
@ -54,44 +54,44 @@ describe HTTParty::ConnectionAdapter do
describe "the resulting connection" do
subject { adapter.connection }
it { should be_an_instance_of Net::HTTP }
it { is_expected.to be_an_instance_of Net::HTTP }
context "using port 80" do
let(:uri) { URI 'http://foobar.com' }
it { should_not use_ssl }
it { is_expected.not_to use_ssl }
end
context "when dealing with ssl" do
let(:uri) { URI 'https://foobar.com' }
context "uses the system cert_store, by default" do
let(:system_cert_store) do
system_cert_store = mock('default_cert_store')
system_cert_store.should_receive(:set_default_paths)
OpenSSL::X509::Store.should_receive(:new).and_return(system_cert_store)
let!(:system_cert_store) do
system_cert_store = double('default_cert_store')
expect(system_cert_store).to receive(:set_default_paths)
expect(OpenSSL::X509::Store).to receive(:new).and_return(system_cert_store)
system_cert_store
end
it { should use_cert_store(system_cert_store) }
it { is_expected.to use_cert_store(system_cert_store) }
end
context "should use the specified cert store, when one is given" do
let(:custom_cert_store) { mock('custom_cert_store') }
let(:custom_cert_store) { double('custom_cert_store') }
let(:options) { {cert_store: custom_cert_store} }
it { should use_cert_store(custom_cert_store) }
it { is_expected.to use_cert_store(custom_cert_store) }
end
context "using port 443 for ssl" do
let(:uri) { URI 'https://api.foo.com/v1:443' }
it { should use_ssl }
it { is_expected.to use_ssl }
end
context "https scheme with default port" do
it { should use_ssl }
it { is_expected.to use_ssl }
end
context "https scheme with non-standard port" do
let(:uri) { URI 'https://foobar.com:123456' }
it { should use_ssl }
it { is_expected.to use_ssl }
end
@ -99,7 +99,7 @@ describe HTTParty::ConnectionAdapter do
let(:options) { {ssl_version: :TLSv1} }
it "sets ssl version" do
subject.ssl_version.should == :TLSv1
expect(subject.ssl_version).to eq(:TLSv1)
end
end if RUBY_VERSION > '1.9'
end
@ -108,7 +108,7 @@ describe HTTParty::ConnectionAdapter do
let(:uri) { URI 'http://[fd00::1]' }
it "strips brackets from the address" do
subject.address.should == 'fd00::1'
expect(subject.address).to eq('fd00::1')
end
end
@ -116,16 +116,21 @@ describe HTTParty::ConnectionAdapter do
let(:options) { {ciphers: 'RC4-SHA' } }
it "should set the ciphers on the connection" do
subject.ciphers.should == 'RC4-SHA'
expect(subject.ciphers).to eq('RC4-SHA')
end
end if RUBY_VERSION > '1.9'
context "when timeout is not set" do
it "doesn't set the timeout" do
http = mock("http", null_object: true)
http.should_not_receive(:open_timeout=)
http.should_not_receive(:read_timeout=)
Net::HTTP.stub(new: http)
http = double(
"http",
:null_object => true,
:use_ssl= => false,
:use_ssl? => false
)
expect(http).not_to receive(:open_timeout=)
expect(http).not_to receive(:read_timeout=)
allow(Net::HTTP).to receive_messages(new: http)
adapter.connection
end
@ -135,18 +140,30 @@ describe HTTParty::ConnectionAdapter do
context "to 5 seconds" do
let(:options) { {timeout: 5} }
its(:open_timeout) { should == 5 }
its(:read_timeout) { should == 5 }
describe '#open_timeout' do
subject { super().open_timeout }
it { is_expected.to eq(5) }
end
describe '#read_timeout' do
subject { super().read_timeout }
it { is_expected.to eq(5) }
end
end
context "and timeout is a string" do
let(:options) { {timeout: "five seconds"} }
it "doesn't set the timeout" do
http = mock("http", null_object: true)
http.should_not_receive(:open_timeout=)
http.should_not_receive(:read_timeout=)
Net::HTTP.stub(new: http)
http = double(
"http",
:null_object => true,
:use_ssl= => false,
:use_ssl? => false
)
expect(http).not_to receive(:open_timeout=)
expect(http).not_to receive(:read_timeout=)
allow(Net::HTTP).to receive_messages(new: http)
adapter.connection
end
@ -156,12 +173,21 @@ describe HTTParty::ConnectionAdapter do
context "when timeout is not set and read_timeout is set to 6 seconds" do
let(:options) { {read_timeout: 6} }
its(:read_timeout) { should == 6 }
describe '#read_timeout' do
subject { super().read_timeout }
it { is_expected.to eq(6) }
end
it "should not set the open_timeout" do
http = mock("http", null_object: true)
http.should_not_receive(:open_timeout=)
Net::HTTP.stub(new: http)
http = double(
"http",
:null_object => true,
:use_ssl= => false,
:use_ssl? => false,
:read_timeout= => 0
)
expect(http).not_to receive(:open_timeout=)
allow(Net::HTTP).to receive_messages(new: http)
adapter.connection
end
end
@ -169,14 +195,28 @@ describe HTTParty::ConnectionAdapter do
context "when timeout is set and read_timeout is set to 6 seconds" do
let(:options) { {timeout: 5, read_timeout: 6} }
its(:open_timeout) { should == 5 }
its(:read_timeout) { should == 6 }
describe '#open_timeout' do
subject { super().open_timeout }
it { is_expected.to eq(5) }
end
describe '#read_timeout' do
subject { super().read_timeout }
it { is_expected.to eq(6) }
end
it "should override the timeout option" do
http = mock("http", null_object: true)
http.should_receive(:open_timeout=)
http.should_receive(:read_timeout=).twice
Net::HTTP.stub(new: http)
http = double(
"http",
:null_object => true,
:use_ssl= => false,
:use_ssl? => false,
:read_timeout= => 0,
:open_timeout= => 0
)
expect(http).to receive(:open_timeout=)
expect(http).to receive(:read_timeout=).twice
allow(Net::HTTP).to receive_messages(new: http)
adapter.connection
end
end
@ -184,12 +224,21 @@ describe HTTParty::ConnectionAdapter do
context "when timeout is not set and open_timeout is set to 7 seconds" do
let(:options) { {open_timeout: 7} }
its(:open_timeout) { should == 7 }
describe '#open_timeout' do
subject { super().open_timeout }
it { is_expected.to eq(7) }
end
it "should not set the read_timeout" do
http = mock("http", null_object: true)
http.should_not_receive(:read_timeout=)
Net::HTTP.stub(new: http)
http = double(
"http",
:null_object => true,
:use_ssl= => false,
:use_ssl? => false,
:open_timeout= => 0
)
expect(http).not_to receive(:read_timeout=)
allow(Net::HTTP).to receive_messages(new: http)
adapter.connection
end
end
@ -197,14 +246,28 @@ describe HTTParty::ConnectionAdapter do
context "when timeout is set and open_timeout is set to 7 seconds" do
let(:options) { {timeout: 5, open_timeout: 7} }
its(:open_timeout) { should == 7 }
its(:read_timeout) { should == 5 }
describe '#open_timeout' do
subject { super().open_timeout }
it { is_expected.to eq(7) }
end
describe '#read_timeout' do
subject { super().read_timeout }
it { is_expected.to eq(5) }
end
it "should override the timeout option" do
http = mock("http", null_object: true)
http.should_receive(:open_timeout=).twice
http.should_receive(:read_timeout=)
Net::HTTP.stub(new: http)
http = double(
"http",
:null_object => true,
:use_ssl= => false,
:use_ssl? => false,
:read_timeout= => 0,
:open_timeout= => 0
)
expect(http).to receive(:open_timeout=).twice
expect(http).to receive(:read_timeout=)
allow(Net::HTTP).to receive_messages(new: http)
adapter.connection
end
end
@ -212,20 +275,20 @@ describe HTTParty::ConnectionAdapter do
context "when debug_output" do
let(:http) { Net::HTTP.new(uri) }
before do
Net::HTTP.stub(new: http)
allow(Net::HTTP).to receive_messages(new: http)
end
context "is set to $stderr" do
let(:options) { {debug_output: $stderr} }
it "has debug output set" do
http.should_receive(:set_debug_output).with($stderr)
expect(http).to receive(:set_debug_output).with($stderr)
adapter.connection
end
end
context "is not provided" do
it "does not set_debug_output" do
http.should_not_receive(:set_debug_output)
expect(http).not_to receive(:set_debug_output)
adapter.connection
end
end
@ -234,17 +297,33 @@ describe HTTParty::ConnectionAdapter do
context 'when providing proxy address and port' do
let(:options) { {http_proxyaddr: '1.2.3.4', http_proxyport: 8080} }
it { should be_a_proxy }
its(:proxy_address) { should == '1.2.3.4' }
its(:proxy_port) { should == 8080 }
it { is_expected.to be_a_proxy }
describe '#proxy_address' do
subject { super().proxy_address }
it { is_expected.to eq('1.2.3.4') }
end
describe '#proxy_port' do
subject { super().proxy_port }
it { is_expected.to eq(8080) }
end
context 'as well as proxy user and password' do
let(:options) do
{http_proxyaddr: '1.2.3.4', http_proxyport: 8080,
http_proxyuser: 'user', http_proxypass: 'pass'}
end
its(:proxy_user) { should == 'user' }
its(:proxy_pass) { should == 'pass' }
describe '#proxy_user' do
subject { super().proxy_user }
it { is_expected.to eq('user') }
end
describe '#proxy_pass' do
subject { super().proxy_pass }
it { is_expected.to eq('pass') }
end
end
end
@ -253,7 +332,7 @@ describe HTTParty::ConnectionAdapter do
it "does not pass any proxy parameters to the connection" do
http = Net::HTTP.new("proxytest.com")
Net::HTTP.should_receive(:new).once.with("proxytest.com", 80).and_return(http)
expect(Net::HTTP).to receive(:new).once.with("proxytest.com", 80).and_return(http)
adapter.connection
end
end
@ -261,8 +340,15 @@ describe HTTParty::ConnectionAdapter do
context 'when providing a local bind address and port' do
let(:options) { {local_host: "127.0.0.1", local_port: 12345 } }
its(:local_host) { should == '127.0.0.1' }
its(:local_port) { should == 12345 }
describe '#local_host' do
subject { super().local_host }
it { is_expected.to eq('127.0.0.1') }
end
describe '#local_port' do
subject { super().local_port }
it { is_expected.to eq(12345) }
end
end if RUBY_VERSION >= '2.0'
context "when providing PEM certificates" do
@ -271,28 +357,28 @@ describe HTTParty::ConnectionAdapter do
context "when scheme is https" do
let(:uri) { URI 'https://google.com' }
let(:cert) { mock("OpenSSL::X509::Certificate") }
let(:key) { mock("OpenSSL::PKey::RSA") }
let(:cert) { double("OpenSSL::X509::Certificate") }
let(:key) { double("OpenSSL::PKey::RSA") }
before do
OpenSSL::X509::Certificate.should_receive(:new).with(pem).and_return(cert)
OpenSSL::PKey::RSA.should_receive(:new).with(pem, "password").and_return(key)
expect(OpenSSL::X509::Certificate).to receive(:new).with(pem).and_return(cert)
expect(OpenSSL::PKey::RSA).to receive(:new).with(pem, "password").and_return(key)
end
it "uses the provided PEM certificate" do
subject.cert.should == cert
subject.key.should == key
expect(subject.cert).to eq(cert)
expect(subject.key).to eq(key)
end
it "will verify the certificate" do
subject.verify_mode.should == OpenSSL::SSL::VERIFY_PEER
expect(subject.verify_mode).to eq(OpenSSL::SSL::VERIFY_PEER)
end
context "when options include verify_peer=false" do
let(:options) { {pem: pem, pem_password: "password", verify_peer: false} }
it "should not verify the certificate" do
subject.verify_mode.should == OpenSSL::SSL::VERIFY_NONE
expect(subject.verify_mode).to eq(OpenSSL::SSL::VERIFY_NONE)
end
end
end
@ -302,16 +388,16 @@ describe HTTParty::ConnectionAdapter do
let(:http) { Net::HTTP.new(uri) }
before do
Net::HTTP.stub(new: http)
OpenSSL::X509::Certificate.should_not_receive(:new).with(pem)
OpenSSL::PKey::RSA.should_not_receive(:new).with(pem, "password")
http.should_not_receive(:cert=)
http.should_not_receive(:key=)
allow(Net::HTTP).to receive_messages(new: http)
expect(OpenSSL::X509::Certificate).not_to receive(:new).with(pem)
expect(OpenSSL::PKey::RSA).not_to receive(:new).with(pem, "password")
expect(http).not_to receive(:cert=)
expect(http).not_to receive(:key=)
end
it "has no PEM certificate " do
subject.cert.should be_nil
subject.key.should be_nil
expect(subject.cert).to be_nil
expect(subject.key).to be_nil
end
end
end
@ -322,28 +408,28 @@ describe HTTParty::ConnectionAdapter do
context "when scheme is https" do
let(:uri) { URI 'https://google.com' }
let(:pkcs12) { mock("OpenSSL::PKCS12", certificate: cert, key: key) }
let(:cert) { mock("OpenSSL::X509::Certificate") }
let(:key) { mock("OpenSSL::PKey::RSA") }
let(:pkcs12) { double("OpenSSL::PKCS12", certificate: cert, key: key) }
let(:cert) { double("OpenSSL::X509::Certificate") }
let(:key) { double("OpenSSL::PKey::RSA") }
before do
OpenSSL::PKCS12.should_receive(:new).with(p12, "password").and_return(pkcs12)
expect(OpenSSL::PKCS12).to receive(:new).with(p12, "password").and_return(pkcs12)
end
it "uses the provided P12 certificate " do
subject.cert.should == cert
subject.key.should == key
expect(subject.cert).to eq(cert)
expect(subject.key).to eq(key)
end
it "will verify the certificate" do
subject.verify_mode.should == OpenSSL::SSL::VERIFY_PEER
expect(subject.verify_mode).to eq(OpenSSL::SSL::VERIFY_PEER)
end
context "when options include verify_peer=false" do
let(:options) { {p12: p12, p12_password: "password", verify_peer: false} }
it "should not verify the certificate" do
subject.verify_mode.should == OpenSSL::SSL::VERIFY_NONE
expect(subject.verify_mode).to eq(OpenSSL::SSL::VERIFY_NONE)
end
end
end
@ -353,15 +439,15 @@ describe HTTParty::ConnectionAdapter do
let(:http) { Net::HTTP.new(uri) }
before do
Net::HTTP.stub(new: http)
OpenSSL::PKCS12.new.should_not_receive(:new).with(p12, "password")
http.should_not_receive(:cert=)
http.should_not_receive(:key=)
allow(Net::HTTP).to receive_messages(new: http)
expect(OpenSSL::PKCS12).not_to receive(:new).with(p12, "password")
expect(http).not_to receive(:cert=)
expect(http).not_to receive(:key=)
end
it "has no PKCS12 certificate " do
subject.cert.should be_nil
subject.key.should be_nil
expect(subject.cert).to be_nil
expect(subject.key).to be_nil
end
end
end

View file

@ -1,6 +1,6 @@
require File.expand_path(File.join(File.dirname(__FILE__), '../spec_helper'))
describe HTTParty::CookieHash do
RSpec.describe HTTParty::CookieHash do
before(:each) do
@cookie_hash = HTTParty::CookieHash.new
end
@ -10,45 +10,45 @@ describe HTTParty::CookieHash do
it "should add new key/value pairs to the hash" do
@cookie_hash.add_cookies(foo: "bar")
@cookie_hash.add_cookies(rofl: "copter")
@cookie_hash.length.should eql(2)
expect(@cookie_hash.length).to eql(2)
end
it "should overwrite any existing key" do
@cookie_hash.add_cookies(foo: "bar")
@cookie_hash.add_cookies(foo: "copter")
@cookie_hash.length.should eql(1)
@cookie_hash[:foo].should eql("copter")
expect(@cookie_hash.length).to eql(1)
expect(@cookie_hash[:foo]).to eql("copter")
end
end
describe "with a string" do
it "should add new key/value pairs to the hash" do
@cookie_hash.add_cookies("first=one; second=two; third")
@cookie_hash[:first].should == 'one'
@cookie_hash[:second].should == 'two'
@cookie_hash[:third].should == nil
expect(@cookie_hash[:first]).to eq('one')
expect(@cookie_hash[:second]).to eq('two')
expect(@cookie_hash[:third]).to eq(nil)
end
it "should overwrite any existing key" do
@cookie_hash[:foo] = 'bar'
@cookie_hash.add_cookies("foo=tar")
@cookie_hash.length.should eql(1)
@cookie_hash[:foo].should eql("tar")
expect(@cookie_hash.length).to eql(1)
expect(@cookie_hash[:foo]).to eql("tar")
end
it "should handle '=' within cookie value" do
@cookie_hash.add_cookies("first=one=1; second=two=2==")
@cookie_hash.keys.should include(:first, :second)
@cookie_hash[:first].should == 'one=1'
@cookie_hash[:second].should == 'two=2=='
expect(@cookie_hash.keys).to include(:first, :second)
expect(@cookie_hash[:first]).to eq('one=1')
expect(@cookie_hash[:second]).to eq('two=2==')
end
end
describe 'with other class' do
it "should error" do
lambda {
expect {
@cookie_hash.add_cookies(Array.new)
}.should raise_error
}.to raise_error
end
end
end
@ -63,21 +63,21 @@ describe HTTParty::CookieHash do
end
it "should format the key/value pairs, delimited by semi-colons" do
@s.should match(/foo=bar/)
@s.should match(/rofl=copter/)
@s.should match(/^\w+=\w+; \w+=\w+$/)
expect(@s).to match(/foo=bar/)
expect(@s).to match(/rofl=copter/)
expect(@s).to match(/^\w+=\w+; \w+=\w+$/)
end
it "should not include client side only cookies" do
@cookie_hash.add_cookies(path: "/")
@s = @cookie_hash.to_cookie_string
@s.should_not match(/path=\//)
expect(@s).not_to match(/path=\//)
end
it "should not include client side only cookies even when attributes use camal case" do
@cookie_hash.add_cookies(Path: "/")
@s = @cookie_hash.to_cookie_string
@s.should_not match(/Path=\//)
expect(@s).not_to match(/Path=\//)
end
end
end

View file

@ -1,23 +1,38 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
describe HTTParty::Error do
RSpec.describe HTTParty::Error do
subject { described_class }
its(:ancestors) { should include(StandardError) }
describe '#ancestors' do
subject { super().ancestors }
it { is_expected.to include(StandardError) }
end
describe HTTParty::UnsupportedFormat do
its(:ancestors) { should include(HTTParty::Error) }
describe '#ancestors' do
subject { super().ancestors }
it { is_expected.to include(HTTParty::Error) }
end
end
describe HTTParty::UnsupportedURIScheme do
its(:ancestors) { should include(HTTParty::Error) }
describe '#ancestors' do
subject { super().ancestors }
it { is_expected.to include(HTTParty::Error) }
end
end
describe HTTParty::ResponseError do
its(:ancestors) { should include(HTTParty::Error) }
describe '#ancestors' do
subject { super().ancestors }
it { is_expected.to include(HTTParty::Error) }
end
end
describe HTTParty::RedirectionTooDeep do
its(:ancestors) { should include(HTTParty::ResponseError) }
describe '#ancestors' do
subject { super().ancestors }
it { is_expected.to include(HTTParty::ResponseError) }
end
end
end

View file

@ -1,6 +1,6 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'spec_helper'))
describe HTTParty::Logger::ApacheLogger do
RSpec.describe HTTParty::Logger::ApacheLogger do
let(:subject) { described_class.new(logger_double, :info) }
let(:logger_double) { double('Logger') }
let(:request_double) { double('Request', http_method: Net::HTTP::Get, path: "http://my.domain.com/my_path") }
@ -8,7 +8,7 @@ describe HTTParty::Logger::ApacheLogger do
before do
subject.current_time = request_time
logger_double.should_receive(:info).with(log_message)
expect(logger_double).to receive(:info).with(log_message)
end
describe "#format" do
@ -32,7 +32,7 @@ describe HTTParty::Logger::ApacheLogger do
code: 200,
headers: { 'Content-Length' => 512 }
)
response_double.stub(:[]).with('Content-Length').and_raise(TypeError.new('no implicit conversion of String into Integer'))
allow(response_double).to receive(:[]).with('Content-Length').and_raise(TypeError.new('no implicit conversion of String into Integer'))
subject.format(request_double, response_double)
end

View file

@ -1,10 +1,10 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'spec_helper'))
describe HTTParty::Logger::CurlLogger do
RSpec.describe HTTParty::Logger::CurlLogger do
describe "#format" do
it "formats a response in a style that resembles a -v curl" do
logger_double = double
logger_double.should_receive(:info).with(
expect(logger_double).to receive(:info).with(
/\[HTTParty\] \[\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\ [+-]\d{4}\] > GET http:\/\/localhost/)
subject = described_class.new(logger_double, :info)

View file

@ -1,22 +1,22 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'spec_helper'))
describe HTTParty::Logger do
RSpec.describe HTTParty::Logger do
describe ".build" do
subject { HTTParty::Logger }
it "defaults level to :info" do
logger_double = double()
subject.build(logger_double, nil, nil).level.should == :info
expect(subject.build(logger_double, nil, nil).level).to eq(:info)
end
it "defaults format to :apache" do
logger_double = double()
subject.build(logger_double, nil, nil).should be_an_instance_of(HTTParty::Logger::ApacheLogger)
expect(subject.build(logger_double, nil, nil)).to be_an_instance_of(HTTParty::Logger::ApacheLogger)
end
it "builds :curl style logger" do
logger_double = double()
subject.build(logger_double, nil, :curl).should be_an_instance_of(HTTParty::Logger::CurlLogger)
expect(subject.build(logger_double, nil, :curl)).to be_an_instance_of(HTTParty::Logger::CurlLogger)
end
end
end

View file

@ -1,11 +1,11 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
describe Net::HTTPHeader::DigestAuthenticator do
RSpec.describe Net::HTTPHeader::DigestAuthenticator do
def setup_digest(response)
digest = Net::HTTPHeader::DigestAuthenticator.new("Mufasa",
"Circle Of Life", "GET", "/dir/index.html", response)
digest.stub(:random).and_return("deadbeef")
Digest::MD5.stub(:hexdigest) { |str| "md5(#{str})" }
allow(digest).to receive(:random).and_return("deadbeef")
allow(Digest::MD5).to receive(:hexdigest) { |str| "md5(#{str})" }
digest
end
@ -22,7 +22,7 @@ describe Net::HTTPHeader::DigestAuthenticator do
end
it "should set opaque" do
authorization_header.should include(%Q(opaque="solid"))
expect(authorization_header).to include(%Q(opaque="solid"))
end
end
@ -34,7 +34,7 @@ describe Net::HTTPHeader::DigestAuthenticator do
end
it "should not set opaque" do
authorization_header.should_not include(%Q(opaque=))
expect(authorization_header).not_to include(%Q(opaque=))
end
end
@ -46,32 +46,32 @@ describe Net::HTTPHeader::DigestAuthenticator do
end
it "should set prefix" do
authorization_header.should =~ /^Digest /
expect(authorization_header).to match(/^Digest /)
end
it "should set username" do
authorization_header.should include(%Q(username="Mufasa"))
expect(authorization_header).to include(%Q(username="Mufasa"))
end
it "should set digest-uri" do
authorization_header.should include(%Q(uri="/dir/index.html"))
expect(authorization_header).to include(%Q(uri="/dir/index.html"))
end
it "should set qop" do
authorization_header.should include(%Q(qop="auth"))
expect(authorization_header).to include(%Q(qop="auth"))
end
it "should set cnonce" do
authorization_header.should include(%Q(cnonce="md5(deadbeef)"))
expect(authorization_header).to include(%Q(cnonce="md5(deadbeef)"))
end
it "should set nonce-count" do
authorization_header.should include(%Q(nc=00000001))
expect(authorization_header).to include(%Q(nc=00000001))
end
it "should set response" do
request_digest = "md5(md5(Mufasa:myhost@testrealm.com:Circle Of Life):NONCE:00000001:md5(deadbeef):auth:md5(GET:/dir/index.html))"
authorization_header.should include(%Q(response="#{request_digest}"))
expect(authorization_header).to include(%Q(response="#{request_digest}"))
end
end
@ -83,7 +83,7 @@ describe Net::HTTPHeader::DigestAuthenticator do
end
it "should still set qop" do
authorization_header.should include(%Q(qop="auth"))
expect(authorization_header).to include(%Q(qop="auth"))
end
end
@ -95,32 +95,32 @@ describe Net::HTTPHeader::DigestAuthenticator do
end
it "should set prefix" do
authorization_header.should =~ /^Digest /
expect(authorization_header).to match(/^Digest /)
end
it "should set username" do
authorization_header.should include(%Q(username="Mufasa"))
expect(authorization_header).to include(%Q(username="Mufasa"))
end
it "should set digest-uri" do
authorization_header.should include(%Q(uri="/dir/index.html"))
expect(authorization_header).to include(%Q(uri="/dir/index.html"))
end
it "should not set qop" do
authorization_header.should_not include(%Q(qop=))
expect(authorization_header).not_to include(%Q(qop=))
end
it "should not set cnonce" do
authorization_header.should_not include(%Q(cnonce=))
expect(authorization_header).not_to include(%Q(cnonce=))
end
it "should not set nonce-count" do
authorization_header.should_not include(%Q(nc=))
expect(authorization_header).not_to include(%Q(nc=))
end
it "should set response" do
request_digest = "md5(md5(Mufasa:myhost@testrealm.com:Circle Of Life):NONCE:md5(GET:/dir/index.html))"
authorization_header.should include(%Q(response="#{request_digest}"))
expect(authorization_header).to include(%Q(response="#{request_digest}"))
end
end
@ -132,32 +132,32 @@ describe Net::HTTPHeader::DigestAuthenticator do
end
it "should set prefix" do
authorization_header.should =~ /^Digest /
expect(authorization_header).to match(/^Digest /)
end
it "should set username" do
authorization_header.should include(%Q(username="Mufasa"))
expect(authorization_header).to include(%Q(username="Mufasa"))
end
it "should set digest-uri" do
authorization_header.should include(%Q(uri="/dir/index.html"))
expect(authorization_header).to include(%Q(uri="/dir/index.html"))
end
it "should set qop" do
authorization_header.should include(%Q(qop="auth"))
expect(authorization_header).to include(%Q(qop="auth"))
end
it "should set cnonce" do
authorization_header.should include(%Q(cnonce="md5(deadbeef)"))
expect(authorization_header).to include(%Q(cnonce="md5(deadbeef)"))
end
it "should set nonce-count" do
authorization_header.should include(%Q(nc=00000001))
expect(authorization_header).to include(%Q(nc=00000001))
end
it "should set response" do
request_digest = "md5(md5(Mufasa:myhost@testrealm.com:Circle Of Life):NONCE:00000001:md5(deadbeef):auth:md5(GET:/dir/index.html))"
authorization_header.should include(%Q(response="#{request_digest}"))
expect(authorization_header).to include(%Q(response="#{request_digest}"))
end
end
end

View file

@ -1,64 +1,64 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
describe HTTParty::Parser do
RSpec.describe HTTParty::Parser do
describe ".SupportedFormats" do
it "returns a hash" do
HTTParty::Parser::SupportedFormats.should be_instance_of(Hash)
expect(HTTParty::Parser::SupportedFormats).to be_instance_of(Hash)
end
end
describe ".call" do
it "generates an HTTParty::Parser instance with the given body and format" do
HTTParty::Parser.should_receive(:new).with('body', :plain).and_return(stub(parse: nil))
expect(HTTParty::Parser).to receive(:new).with('body', :plain).and_return(double(parse: nil))
HTTParty::Parser.call('body', :plain)
end
it "calls #parse on the parser" do
parser = mock('Parser')
parser.should_receive(:parse)
HTTParty::Parser.stub(new: parser)
parser = double('Parser')
expect(parser).to receive(:parse)
allow(HTTParty::Parser).to receive_messages(new: parser)
parser = HTTParty::Parser.call('body', :plain)
end
end
describe ".formats" do
it "returns the SupportedFormats constant" do
HTTParty::Parser.formats.should == HTTParty::Parser::SupportedFormats
expect(HTTParty::Parser.formats).to eq(HTTParty::Parser::SupportedFormats)
end
it "returns the SupportedFormats constant for subclasses" do
class MyParser < HTTParty::Parser
SupportedFormats = {"application/atom+xml" => :atom}
end
MyParser.formats.should == {"application/atom+xml" => :atom}
expect(MyParser.formats).to eq({"application/atom+xml" => :atom})
end
end
describe ".format_from_mimetype" do
it "returns a symbol representing the format mimetype" do
HTTParty::Parser.format_from_mimetype("text/plain").should == :plain
expect(HTTParty::Parser.format_from_mimetype("text/plain")).to eq(:plain)
end
it "returns nil when the mimetype is not supported" do
HTTParty::Parser.format_from_mimetype("application/atom+xml").should be_nil
expect(HTTParty::Parser.format_from_mimetype("application/atom+xml")).to be_nil
end
end
describe ".supported_formats" do
it "returns a unique set of supported formats represented by symbols" do
HTTParty::Parser.supported_formats.should == HTTParty::Parser::SupportedFormats.values.uniq
expect(HTTParty::Parser.supported_formats).to eq(HTTParty::Parser::SupportedFormats.values.uniq)
end
end
describe ".supports_format?" do
it "returns true for a supported format" do
HTTParty::Parser.stub(supported_formats: [:json])
HTTParty::Parser.supports_format?(:json).should be_true
allow(HTTParty::Parser).to receive_messages(supported_formats: [:json])
expect(HTTParty::Parser.supports_format?(:json)).to be_truthy
end
it "returns false for an unsupported format" do
HTTParty::Parser.stub(supported_formats: [])
HTTParty::Parser.supports_format?(:json).should be_false
allow(HTTParty::Parser).to receive_messages(supported_formats: [])
expect(HTTParty::Parser.supports_format?(:json)).to be_falsey
end
end
@ -68,40 +68,40 @@ describe HTTParty::Parser do
end
it "attempts to parse supported formats" do
@parser.stub(supports_format?: true)
@parser.should_receive(:parse_supported_format)
allow(@parser).to receive_messages(supports_format?: true)
expect(@parser).to receive(:parse_supported_format)
@parser.parse
end
it "returns the unparsed body when the format is unsupported" do
@parser.stub(supports_format?: false)
@parser.parse.should == @parser.body
allow(@parser).to receive_messages(supports_format?: false)
expect(@parser.parse).to eq(@parser.body)
end
it "returns nil for an empty body" do
@parser.stub(body: '')
@parser.parse.should be_nil
allow(@parser).to receive_messages(body: '')
expect(@parser.parse).to be_nil
end
it "returns nil for a nil body" do
@parser.stub(body: nil)
@parser.parse.should be_nil
allow(@parser).to receive_messages(body: nil)
expect(@parser.parse).to be_nil
end
it "returns nil for a 'null' body" do
@parser.stub(body: "null")
@parser.parse.should be_nil
allow(@parser).to receive_messages(body: "null")
expect(@parser.parse).to be_nil
end
it "returns nil for a body with spaces only" do
@parser.stub(body: " ")
@parser.parse.should be_nil
allow(@parser).to receive_messages(body: " ")
expect(@parser.parse).to be_nil
end
end
describe "#supports_format?" do
it "utilizes the class method to determine if the format is supported" do
HTTParty::Parser.should_receive(:supports_format?).with(:json)
expect(HTTParty::Parser).to receive(:supports_format?).with(:json)
parser = HTTParty::Parser.new('body', :json)
parser.send(:supports_format?)
end
@ -110,7 +110,7 @@ describe HTTParty::Parser do
describe "#parse_supported_format" do
it "calls the parser for the given format" do
parser = HTTParty::Parser.new('body', :json)
parser.should_receive(:json)
expect(parser).to receive(:json)
parser.send(:parse_supported_format)
end
@ -140,25 +140,25 @@ describe HTTParty::Parser do
end
it "parses xml with MultiXml" do
MultiXml.should_receive(:parse).with('body')
expect(MultiXml).to receive(:parse).with('body')
subject.send(:xml)
end
it "parses json with JSON" do
JSON.should_receive(:load).with('body', nil)
expect(JSON).to receive(:load).with('body', nil)
subject.send(:json)
end
it "parses html by simply returning the body" do
subject.send(:html).should == 'body'
expect(subject.send(:html)).to eq('body')
end
it "parses plain text by simply returning the body" do
subject.send(:plain).should == 'body'
expect(subject.send(:plain)).to eq('body')
end
it "parses csv with CSV" do
CSV.should_receive(:parse).with('body')
expect(CSV).to receive(:parse).with('body')
subject.send(:csv)
end
end

View file

@ -1,6 +1,6 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
describe HTTParty::Request do
RSpec.describe HTTParty::Request do
before do
@request = HTTParty::Request.new(Net::HTTP::Get, 'http://api.foo.com/v1', format: :xml)
end
@ -10,26 +10,26 @@ describe HTTParty::Request do
it "doesn't modify strings" do
query_string = normalizer["foo=bar&foo=baz"]
URI.unescape(query_string).should == "foo=bar&foo=baz"
expect(URI.unescape(query_string)).to eq("foo=bar&foo=baz")
end
context "when the query is an array" do
it "doesn't include brackets" do
query_string = normalizer[{page: 1, foo: %w(bar baz)}]
URI.unescape(query_string).should == "foo=bar&foo=baz&page=1"
expect(URI.unescape(query_string)).to eq("foo=bar&foo=baz&page=1")
end
it "URI encodes array values" do
query_string = normalizer[{people: ["Otis Redding", "Bob Marley", "Tim & Jon"], page: 1, xyzzy: 3}]
query_string.should == "page=1&people=Otis%20Redding&people=Bob%20Marley&people=Tim%20%26%20Jon&xyzzy=3"
expect(query_string).to eq("page=1&people=Otis%20Redding&people=Bob%20Marley&people=Tim%20%26%20Jon&xyzzy=3")
end
end
context "when the query is a hash" do
it "correctly handles nil values" do
query_string = normalizer[{page: 1, per_page: nil}]
query_string.should == "page=1&per_page"
expect(query_string).to eq("page=1&per_page")
end
end
end
@ -37,31 +37,31 @@ describe HTTParty::Request do
describe "initialization" do
it "sets parser to HTTParty::Parser" do
request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com')
request.parser.should == HTTParty::Parser
expect(request.parser).to eq(HTTParty::Parser)
end
it "sets parser to the optional parser" do
my_parser = lambda {}
request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', parser: my_parser)
request.parser.should == my_parser
expect(request.parser).to eq(my_parser)
end
it "sets connection_adapter to HTTPParty::ConnectionAdapter" do
request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com')
request.connection_adapter.should == HTTParty::ConnectionAdapter
expect(request.connection_adapter).to eq(HTTParty::ConnectionAdapter)
end
it "sets connection_adapter to the optional connection_adapter" do
my_adapter = lambda {}
request = HTTParty::Request.new(Net::HTTP::Get, 'http://google.com', connection_adapter: my_adapter)
request.connection_adapter.should == my_adapter
expect(request.connection_adapter).to eq(my_adapter)
end
context "when basic authentication credentials provided in uri" do
context "when basic auth options wasn't set explicitly" do
it "sets basic auth from uri" do
request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@example.com')
request.options[:basic_auth].should == {:username => 'user1', :password => 'pass1'}
expect(request.options[:basic_auth]).to eq({:username => 'user1', :password => 'pass1'})
end
end
@ -69,7 +69,7 @@ describe HTTParty::Request do
it "uses basic auth from url anyway" do
basic_auth = {:username => 'user2', :password => 'pass2'}
request = HTTParty::Request.new(Net::HTTP::Get, 'http://user1:pass1@example.com', :basic_auth => basic_auth)
request.options[:basic_auth].should == {:username => 'user1', :password => 'pass1'}
expect(request.options[:basic_auth]).to eq({:username => 'user1', :password => 'pass1'})
end
end
end
@ -79,28 +79,28 @@ describe HTTParty::Request do
context "request yet to be made" do
it "returns format option" do
request = HTTParty::Request.new 'get', '/', format: :xml
request.format.should == :xml
expect(request.format).to eq(:xml)
end
it "returns nil format" do
request = HTTParty::Request.new 'get', '/'
request.format.should be_nil
expect(request.format).to be_nil
end
end
context "request has been made" do
it "returns format option" do
request = HTTParty::Request.new 'get', '/', format: :xml
request.last_response = stub
request.format.should == :xml
request.last_response = double
expect(request.format).to eq(:xml)
end
it "returns the content-type from the last response when the option is not set" do
request = HTTParty::Request.new 'get', '/'
response = stub
response.should_receive(:[]).with('content-type').and_return('text/json')
response = double
expect(response).to receive(:[]).with('content-type').and_return('text/json')
request.last_response = response
request.format.should == :json
expect(request.format).to eq(:json)
end
end
@ -110,7 +110,7 @@ describe HTTParty::Request do
it "should use basic auth when configured" do
@request.options[:basic_auth] = {username: 'foobar', password: 'secret'}
@request.send(:setup_raw_request)
@request.instance_variable_get(:@raw_request)['authorization'].should_not be_nil
expect(@request.instance_variable_get(:@raw_request)['authorization']).not_to be_nil
end
it "should use digest auth when configured" do
@ -121,7 +121,7 @@ describe HTTParty::Request do
@request.send(:setup_raw_request)
raw_request = @request.instance_variable_get(:@raw_request)
raw_request.instance_variable_get(:@header)['Authorization'].should_not be_nil
expect(raw_request.instance_variable_get(:@header)['Authorization']).not_to be_nil
end
it "should use the right http method for digest authentication" do
@ -129,8 +129,8 @@ describe HTTParty::Request do
FakeWeb.register_uri(:post, "http://api.foo.com/v1", {})
http = @post_request.send(:http)
@post_request.should_receive(:http).and_return(http)
http.should_not_receive(:head).and_return({'www-authenticate' => nil})
expect(@post_request).to receive(:http).and_return(http)
expect(http).not_to receive(:head).with({'www-authenticate' => nil})
@post_request.options[:digest_auth] = {username: 'foobar', password: 'secret'}
@post_request.send(:setup_raw_request)
end
@ -139,7 +139,7 @@ describe HTTParty::Request do
stream = StringIO.new('foo')
request = HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', body_stream: stream)
request.send(:setup_raw_request)
request.instance_variable_get(:@raw_request).body_stream.should == stream
expect(request.instance_variable_get(:@raw_request).body_stream).to eq(stream)
end
end
@ -150,7 +150,7 @@ describe HTTParty::Request do
@request.path = URI.parse("bar?foo=bar")
@request.redirect = true
@request.uri.should == URI.parse("http://example.com/foo/bar?foo=bar")
expect(@request.uri).to eq(URI.parse("http://example.com/foo/bar?foo=bar"))
end
it "returns correct path when the server sets the location header to an absolute path" do
@ -158,7 +158,7 @@ describe HTTParty::Request do
@request.path = URI.parse("/bar?foo=bar")
@request.redirect = true
@request.uri.should == URI.parse("http://example.com/bar?foo=bar")
expect(@request.uri).to eq(URI.parse("http://example.com/bar?foo=bar"))
end
it "returns correct path when the server sets the location header to a full uri" do
@ -166,39 +166,39 @@ describe HTTParty::Request do
@request.path = URI.parse("http://example.com/bar?foo=bar")
@request.redirect = true
@request.uri.should == URI.parse("http://example.com/bar?foo=bar")
expect(@request.uri).to eq(URI.parse("http://example.com/bar?foo=bar"))
end
end
context "query strings" do
it "does not add an empty query string when default_params are blank" do
@request.options[:default_params] = {}
@request.uri.query.should be_nil
expect(@request.uri.query).to be_nil
end
it "respects the query string normalization proc" do
empty_proc = lambda {|qs| ""}
@request.options[:query_string_normalizer] = empty_proc
@request.options[:query] = {foo: :bar}
URI.unescape(@request.uri.query).should == ""
expect(URI.unescape(@request.uri.query)).to eq("")
end
it "does not append an ampersand when queries are embedded in paths" do
@request.path = "/path?a=1"
@request.options[:query] = {}
@request.uri.query.should == "a=1"
expect(@request.uri.query).to eq("a=1")
end
it "does not duplicate query string parameters when uri is called twice" do
@request.options[:query] = {foo: :bar}
@request.uri
@request.uri.query.should == "foo=bar"
expect(@request.uri.query).to eq("foo=bar")
end
context "when representing an array" do
it "returns a Rails style query string" do
@request.options[:query] = {foo: %w(bar baz)}
URI.unescape(@request.uri.query).should == "foo[]=bar&foo[]=baz"
expect(URI.unescape(@request.uri.query)).to eq("foo[]=bar&foo[]=baz")
end
end
@ -212,7 +212,7 @@ describe HTTParty::Request do
@request.options[:body] = {page: 1, foo: %w(bar baz)}
@request.send(:setup_raw_request)
body = @request.instance_variable_get(:@raw_request).body
URI.unescape(body).should == "foo=bar&foo=baz&page=1"
expect(URI.unescape(body)).to eq("foo=bar&foo=baz&page=1")
end
end
end
@ -220,75 +220,75 @@ describe HTTParty::Request do
describe 'http' do
it "should get a connection from the connection_adapter" do
http = Net::HTTP.new('google.com')
adapter = mock('adapter')
adapter = double('adapter')
request = HTTParty::Request.new(Net::HTTP::Get, 'https://api.foo.com/v1:443', connection_adapter: adapter)
adapter.should_receive(:call).with(request.uri, request.options).and_return(http)
request.send(:http).should be http
expect(adapter).to receive(:call).with(request.uri, request.options).and_return(http)
expect(request.send(:http)).to be http
end
end
describe '#format_from_mimetype' do
it 'should handle text/xml' do
["text/xml", "text/xml; charset=iso8859-1"].each do |ct|
@request.send(:format_from_mimetype, ct).should == :xml
expect(@request.send(:format_from_mimetype, ct)).to eq(:xml)
end
end
it 'should handle application/xml' do
["application/xml", "application/xml; charset=iso8859-1"].each do |ct|
@request.send(:format_from_mimetype, ct).should == :xml
expect(@request.send(:format_from_mimetype, ct)).to eq(:xml)
end
end
it 'should handle text/json' do
["text/json", "text/json; charset=iso8859-1"].each do |ct|
@request.send(:format_from_mimetype, ct).should == :json
expect(@request.send(:format_from_mimetype, ct)).to eq(:json)
end
end
it 'should handle application/json' do
["application/json", "application/json; charset=iso8859-1"].each do |ct|
@request.send(:format_from_mimetype, ct).should == :json
expect(@request.send(:format_from_mimetype, ct)).to eq(:json)
end
end
it 'should handle text/csv' do
["text/csv", "text/csv; charset=iso8859-1"].each do |ct|
@request.send(:format_from_mimetype, ct).should == :csv
expect(@request.send(:format_from_mimetype, ct)).to eq(:csv)
end
end
it 'should handle application/csv' do
["application/csv", "application/csv; charset=iso8859-1"].each do |ct|
@request.send(:format_from_mimetype, ct).should == :csv
expect(@request.send(:format_from_mimetype, ct)).to eq(:csv)
end
end
it 'should handle text/comma-separated-values' do
["text/comma-separated-values", "text/comma-separated-values; charset=iso8859-1"].each do |ct|
@request.send(:format_from_mimetype, ct).should == :csv
expect(@request.send(:format_from_mimetype, ct)).to eq(:csv)
end
end
it 'should handle text/javascript' do
["text/javascript", "text/javascript; charset=iso8859-1"].each do |ct|
@request.send(:format_from_mimetype, ct).should == :plain
expect(@request.send(:format_from_mimetype, ct)).to eq(:plain)
end
end
it 'should handle application/javascript' do
["application/javascript", "application/javascript; charset=iso8859-1"].each do |ct|
@request.send(:format_from_mimetype, ct).should == :plain
expect(@request.send(:format_from_mimetype, ct)).to eq(:plain)
end
end
it "returns nil for an unrecognized mimetype" do
@request.send(:format_from_mimetype, "application/atom+xml").should be_nil
expect(@request.send(:format_from_mimetype, "application/atom+xml")).to be_nil
end
it "returns nil when using a default parser" do
@request.options[:parser] = lambda {}
@request.send(:format_from_mimetype, "text/json").should be_nil
expect(@request.send(:format_from_mimetype, "text/json")).to be_nil
end
end
@ -296,19 +296,19 @@ describe HTTParty::Request do
it 'should handle xml automatically' do
xml = %q[<books><book><id>1234</id><name>Foo Bar!</name></book></books>]
@request.options[:format] = :xml
@request.send(:parse_response, xml).should == {'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}}
expect(@request.send(:parse_response, xml)).to eq({'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}})
end
it 'should handle csv automatically' do
csv=[%q["id","Name"],%q["1234","Foo Bar!"]].join("\n")
@request.options[:format] = :csv
@request.send(:parse_response, csv).should == [["id","Name"],["1234","Foo Bar!"]]
expect(@request.send(:parse_response, csv)).to eq([["id","Name"],["1234","Foo Bar!"]])
end
it 'should handle json automatically' do
json = %q[{"books": {"book": {"name": "Foo Bar!", "id": "1234"}}}]
@request.options[:format] = :json
@request.send(:parse_response, json).should == {'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}}
expect(@request.send(:parse_response, json)).to eq({'books' => {'book' => {'id' => '1234', 'name' => 'Foo Bar!'}}})
end
it "should include any HTTP headers in the returned response" do
@ -316,7 +316,7 @@ describe HTTParty::Request do
response = stub_response "Content"
response.initialize_http_header("key" => "value")
@request.perform.headers.should == { "key" => ["value"] }
expect(@request.perform.headers).to eq({ "key" => ["value"] })
end
if "".respond_to?(:encoding)
@ -325,21 +325,21 @@ describe HTTParty::Request do
response = stub_response "Content"
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-8")
resp = @request.perform
resp.body.encoding.should == Encoding.find("UTF-8")
expect(resp.body.encoding).to eq(Encoding.find("UTF-8"))
end
it "should process charset in content type properly if it has a different case" do
response = stub_response "Content"
response.initialize_http_header("Content-Type" => "text/plain;CHARSET = utf-8")
resp = @request.perform
resp.body.encoding.should == Encoding.find("UTF-8")
expect(resp.body.encoding).to eq(Encoding.find("UTF-8"))
end
it "should process quoted charset in content type properly" do
response = stub_response "Content"
response.initialize_http_header("Content-Type" => "text/plain;charset = \"utf-8\"")
resp = @request.perform
resp.body.encoding.should == Encoding.find("UTF-8")
expect(resp.body.encoding).to eq(Encoding.find("UTF-8"))
end
it "should process utf-16 charset with little endian bom correctly" do
@ -348,7 +348,7 @@ describe HTTParty::Request do
response = stub_response "\xFF\xFEC\x00o\x00n\x00t\x00e\x00n\x00t\x00"
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-16")
resp = @request.perform
resp.body.encoding.should == Encoding.find("UTF-16LE")
expect(resp.body.encoding).to eq(Encoding.find("UTF-16LE"))
end
it "should process utf-16 charset with big endian bom correctly" do
@ -357,7 +357,7 @@ describe HTTParty::Request do
response = stub_response "\xFE\xFF\x00C\x00o\x00n\x00t\x00e\x00n\x00t"
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-16")
resp = @request.perform
resp.body.encoding.should == Encoding.find("UTF-16BE")
expect(resp.body.encoding).to eq(Encoding.find("UTF-16BE"))
end
it "should assume utf-16 little endian if options has been chosen" do
@ -366,7 +366,7 @@ describe HTTParty::Request do
response = stub_response "C\x00o\x00n\x00t\x00e\x00n\x00t\x00"
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-16")
resp = @request.perform
resp.body.encoding.should == Encoding.find("UTF-16LE")
expect(resp.body.encoding).to eq(Encoding.find("UTF-16LE"))
end
@ -375,8 +375,8 @@ describe HTTParty::Request do
response = stub_response "Content"
response.initialize_http_header("Content-Type" => "text/plain;charset = utf-lols")
resp = @request.perform
resp.body.should == "Content"
resp.body.encoding.should == "Content".encoding
expect(resp.body).to eq("Content")
expect(resp.body.encoding).to eq("Content".encoding)
end
it "should perform no encoding if the content type is specified but no charset is specified" do
@ -384,8 +384,8 @@ describe HTTParty::Request do
response = stub_response "Content"
response.initialize_http_header("Content-Type" => "text/plain")
resp = @request.perform
resp.body.should == "Content"
resp.body.encoding.should == "Content".encoding
expect(resp.body).to eq("Content")
expect(resp.body.encoding).to eq("Content".encoding)
end
end
@ -394,22 +394,22 @@ describe HTTParty::Request do
it 'returns a valid object for 304 not modified' do
stub_response '', 304
resp = @request.perform
resp.code.should == 304
resp.body.should == ''
resp.should be_nil
expect(resp.code).to eq(304)
expect(resp.body).to eq('')
expect(resp).to be_nil
end
it "redirects if a 300 contains a location header" do
redirect = stub_response '', 300
redirect['location'] = 'http://foo.com/foo'
ok = stub_response('<hash><foo>bar</foo></hash>', 200)
@http.stub!(:request).and_return(redirect, ok)
allow(@http).to receive(:request).and_return(redirect, ok)
response = @request.perform
response.request.base_uri.to_s.should == "http://foo.com"
response.request.path.to_s.should == "http://foo.com/foo"
response.request.uri.request_uri.should == "/foo"
response.request.uri.to_s.should == "http://foo.com/foo"
response.should == {"hash" => {"foo" => "bar"}}
expect(response.request.base_uri.to_s).to eq("http://foo.com")
expect(response.request.path.to_s).to eq("http://foo.com/foo")
expect(response.request.uri.request_uri).to eq("/foo")
expect(response.request.uri.to_s).to eq("http://foo.com/foo")
expect(response).to include({"hash" => {"foo" => "bar"}})
end
it "calls block given to perform with each redirect" do
@ -418,20 +418,20 @@ describe HTTParty::Request do
FakeWeb.register_uri(:get, "http://api.foo.com/v2", body: "<hash><foo>bar</foo></hash>")
body = ""
response = @request.perform { |chunk| body += chunk }
body.length.should == 27
expect(body.length).to eq(27)
end
it "redirects if a 300 contains a relative location header" do
redirect = stub_response '', 300
redirect['location'] = '/foo/bar'
ok = stub_response('<hash><foo>bar</foo></hash>', 200)
@http.stub!(:request).and_return(redirect, ok)
allow(@http).to receive(:request).and_return(redirect, ok)
response = @request.perform
response.request.base_uri.to_s.should == "http://api.foo.com"
response.request.path.to_s.should == "/foo/bar"
response.request.uri.request_uri.should == "/foo/bar"
response.request.uri.to_s.should == "http://api.foo.com/foo/bar"
response.should == {"hash" => {"foo" => "bar"}}
expect(response.request.base_uri.to_s).to eq("http://api.foo.com")
expect(response.request.path.to_s).to eq("/foo/bar")
expect(response.request.uri.request_uri).to eq("/foo/bar")
expect(response.request.uri.to_s).to eq("http://api.foo.com/foo/bar")
expect(response).to include({"hash" => {"foo" => "bar"}})
end
it "handles multiple redirects and relative location headers on different hosts" do
@ -440,43 +440,43 @@ describe HTTParty::Request do
FakeWeb.register_uri(:get, "http://api.foo.com/v2", status: [300, "REDIRECT"], location: "/v3")
FakeWeb.register_uri(:get, "http://api.foo.com/v3", body: "<hash><foo>bar</foo></hash>")
response = @request.perform
response.request.base_uri.to_s.should == "http://api.foo.com"
response.request.path.to_s.should == "/v3"
response.request.uri.request_uri.should == "/v3"
response.request.uri.to_s.should == "http://api.foo.com/v3"
response.should == {"hash" => {"foo" => "bar"}}
expect(response.request.base_uri.to_s).to eq("http://api.foo.com")
expect(response.request.path.to_s).to eq("/v3")
expect(response.request.uri.request_uri).to eq("/v3")
expect(response.request.uri.to_s).to eq("http://api.foo.com/v3")
expect(response).to include({"hash" => {"foo" => "bar"}})
end
it "returns the HTTParty::Response when the 300 does not contain a location header" do
stub_response '', 300
HTTParty::Response.should === @request.perform
expect(HTTParty::Response).to be === @request.perform
end
end
it 'should return a valid object for 4xx response' do
stub_response '<foo><bar>yes</bar></foo>', 401
resp = @request.perform
resp.code.should == 401
resp.body.should == "<foo><bar>yes</bar></foo>"
resp['foo']['bar'].should == "yes"
expect(resp.code).to eq(401)
expect(resp.body).to eq("<foo><bar>yes</bar></foo>")
expect(resp['foo']['bar']).to eq("yes")
end
it 'should return a valid object for 5xx response' do
stub_response '<foo><bar>error</bar></foo>', 500
resp = @request.perform
resp.code.should == 500
resp.body.should == "<foo><bar>error</bar></foo>"
resp['foo']['bar'].should == "error"
expect(resp.code).to eq(500)
expect(resp.body).to eq("<foo><bar>error</bar></foo>")
expect(resp['foo']['bar']).to eq("error")
end
it "parses response lazily so codes can be checked prior" do
stub_response 'not xml', 500
@request.options[:format] = :xml
lambda {
expect {
response = @request.perform
response.code.should == 500
response.body.should == 'not xml'
}.should_not raise_error
expect(response.code).to eq(500)
expect(response.body).to eq('not xml')
}.not_to raise_error
end
end
end
@ -486,14 +486,14 @@ describe HTTParty::Request do
stub_response "", code
@request.options[:format] = :xml
@request.perform.should be_nil
expect(@request.perform).to be_nil
end
end
it "should not fail for missing mime type" do
stub_response "Content for you"
@request.options[:format] = :html
@request.perform.should == 'Content for you'
expect(@request.perform).to include('Content for you')
end
describe "a request that 302 redirects" do
@ -506,100 +506,100 @@ describe HTTParty::Request do
describe "once" do
before(:each) do
@http.stub!(:request).and_return(@redirect, @ok)
allow(@http).to receive(:request).and_return(@redirect, @ok)
end
it "should be handled by GET transparently" do
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by POST transparently" do
@request.http_method = Net::HTTP::Post
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by DELETE transparently" do
@request.http_method = Net::HTTP::Delete
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by MOVE transparently" do
@request.http_method = Net::HTTP::Move
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by COPY transparently" do
@request.http_method = Net::HTTP::Copy
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by PATCH transparently" do
@request.http_method = Net::HTTP::Patch
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by PUT transparently" do
@request.http_method = Net::HTTP::Put
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by HEAD transparently" do
@request.http_method = Net::HTTP::Head
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by OPTIONS transparently" do
@request.http_method = Net::HTTP::Options
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should keep track of cookies between redirects" do
@redirect['Set-Cookie'] = 'foo=bar; name=value; HTTPOnly'
@request.perform
@request.options[:headers]['Cookie'].should match(/foo=bar/)
@request.options[:headers]['Cookie'].should match(/name=value/)
expect(@request.options[:headers]['Cookie']).to match(/foo=bar/)
expect(@request.options[:headers]['Cookie']).to match(/name=value/)
end
it 'should update cookies with rediects' do
@request.options[:headers] = {'Cookie'=> 'foo=bar;'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
@request.options[:headers]['Cookie'].should match(/foo=tar/)
expect(@request.options[:headers]['Cookie']).to match(/foo=tar/)
end
it 'should keep cookies between rediects' do
@request.options[:headers] = {'Cookie'=> 'keep=me'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
@request.options[:headers]['Cookie'].should match(/keep=me/)
expect(@request.options[:headers]['Cookie']).to match(/keep=me/)
end
it "should handle multiple Set-Cookie headers between redirects" do
@redirect.add_field 'set-cookie', 'foo=bar; name=value; HTTPOnly'
@redirect.add_field 'set-cookie', 'one=1; two=2; HTTPOnly'
@request.perform
@request.options[:headers]['Cookie'].should match(/foo=bar/)
@request.options[:headers]['Cookie'].should match(/name=value/)
@request.options[:headers]['Cookie'].should match(/one=1/)
@request.options[:headers]['Cookie'].should match(/two=2/)
expect(@request.options[:headers]['Cookie']).to match(/foo=bar/)
expect(@request.options[:headers]['Cookie']).to match(/name=value/)
expect(@request.options[:headers]['Cookie']).to match(/one=1/)
expect(@request.options[:headers]['Cookie']).to match(/two=2/)
end
it 'should make resulting request a get request if it not already' do
@request.http_method = Net::HTTP::Delete
@request.perform.should == {"hash" => {"foo" => "bar"}}
@request.http_method.should == Net::HTTP::Get
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Get)
end
it 'should not make resulting request a get request if options[:maintain_method_across_redirects] is true' do
@request.options[:maintain_method_across_redirects] = true
@request.http_method = Net::HTTP::Delete
@request.perform.should == {"hash" => {"foo" => "bar"}}
@request.http_method.should == Net::HTTP::Delete
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Delete)
end
it 'should log the redirection' do
logger_double = double
logger_double.should_receive(:info).twice
expect(logger_double).to receive(:info).twice
@request.options[:logger] = logger_double
@request.perform
end
@ -607,11 +607,11 @@ describe HTTParty::Request do
describe "infinitely" do
before(:each) do
@http.stub!(:request).and_return(@redirect)
allow(@http).to receive(:request).and_return(@redirect)
end
it "should raise an exception" do
lambda { @request.perform }.should raise_error(HTTParty::RedirectionTooDeep)
expect { @request.perform }.to raise_error(HTTParty::RedirectionTooDeep)
end
end
end
@ -626,116 +626,116 @@ describe HTTParty::Request do
describe "once" do
before(:each) do
@http.stub!(:request).and_return(@redirect, @ok)
allow(@http).to receive(:request).and_return(@redirect, @ok)
end
it "should be handled by GET transparently" do
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by POST transparently" do
@request.http_method = Net::HTTP::Post
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by DELETE transparently" do
@request.http_method = Net::HTTP::Delete
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by MOVE transparently" do
@request.http_method = Net::HTTP::Move
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by COPY transparently" do
@request.http_method = Net::HTTP::Copy
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by PATCH transparently" do
@request.http_method = Net::HTTP::Patch
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by PUT transparently" do
@request.http_method = Net::HTTP::Put
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by HEAD transparently" do
@request.http_method = Net::HTTP::Head
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should be handled by OPTIONS transparently" do
@request.http_method = Net::HTTP::Options
@request.perform.should == {"hash" => {"foo" => "bar"}}
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
end
it "should keep track of cookies between redirects" do
@redirect['Set-Cookie'] = 'foo=bar; name=value; HTTPOnly'
@request.perform
@request.options[:headers]['Cookie'].should match(/foo=bar/)
@request.options[:headers]['Cookie'].should match(/name=value/)
expect(@request.options[:headers]['Cookie']).to match(/foo=bar/)
expect(@request.options[:headers]['Cookie']).to match(/name=value/)
end
it 'should update cookies with rediects' do
@request.options[:headers] = {'Cookie'=> 'foo=bar;'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
@request.options[:headers]['Cookie'].should match(/foo=tar/)
expect(@request.options[:headers]['Cookie']).to match(/foo=tar/)
end
it 'should keep cookies between rediects' do
@request.options[:headers] = {'Cookie'=> 'keep=me'}
@redirect['Set-Cookie'] = 'foo=tar;'
@request.perform
@request.options[:headers]['Cookie'].should match(/keep=me/)
expect(@request.options[:headers]['Cookie']).to match(/keep=me/)
end
it "should handle multiple Set-Cookie headers between redirects" do
@redirect.add_field 'set-cookie', 'foo=bar; name=value; HTTPOnly'
@redirect.add_field 'set-cookie', 'one=1; two=2; HTTPOnly'
@request.perform
@request.options[:headers]['Cookie'].should match(/foo=bar/)
@request.options[:headers]['Cookie'].should match(/name=value/)
@request.options[:headers]['Cookie'].should match(/one=1/)
@request.options[:headers]['Cookie'].should match(/two=2/)
expect(@request.options[:headers]['Cookie']).to match(/foo=bar/)
expect(@request.options[:headers]['Cookie']).to match(/name=value/)
expect(@request.options[:headers]['Cookie']).to match(/one=1/)
expect(@request.options[:headers]['Cookie']).to match(/two=2/)
end
it 'should make resulting request a get request if it not already' do
@request.http_method = Net::HTTP::Delete
@request.perform.should == {"hash" => {"foo" => "bar"}}
@request.http_method.should == Net::HTTP::Get
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Get)
end
it 'should make resulting request a get request if options[:maintain_method_across_redirects] is false' do
@request.options[:maintain_method_across_redirects] = false
@request.http_method = Net::HTTP::Delete
@request.perform.should == {"hash" => {"foo" => "bar"}}
@request.http_method.should == Net::HTTP::Get
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Get)
end
it 'should make resulting request a get request if options[:maintain_method_across_redirects] is true but options[:resend_on_redirect] is false' do
@request.options[:maintain_method_across_redirects] = true
@request.options[:resend_on_redirect] = false
@request.http_method = Net::HTTP::Delete
@request.perform.should == {"hash" => {"foo" => "bar"}}
@request.http_method.should == Net::HTTP::Get
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Get)
end
it 'should not make resulting request a get request if options[:maintain_method_across_redirects] and options[:resend_on_redirect] is true' do
@request.options[:maintain_method_across_redirects] = true
@request.options[:resend_on_redirect] = true
@request.http_method = Net::HTTP::Delete
@request.perform.should == {"hash" => {"foo" => "bar"}}
@request.http_method.should == Net::HTTP::Delete
expect(@request.perform).to include({"hash" => {"foo" => "bar"}})
expect(@request.http_method).to eq(Net::HTTP::Delete)
end
it 'should log the redirection' do
logger_double = double
logger_double.should_receive(:info).twice
expect(logger_double).to receive(:info).twice
@request.options[:logger] = logger_double
@request.perform
end
@ -743,11 +743,11 @@ describe HTTParty::Request do
describe "infinitely" do
before(:each) do
@http.stub!(:request).and_return(@redirect)
allow(@http).to receive(:request).and_return(@redirect)
end
it "should raise an exception" do
lambda { @request.perform }.should raise_error(HTTParty::RedirectionTooDeep)
expect { @request.perform }.to raise_error(HTTParty::RedirectionTooDeep)
end
end
end
@ -756,31 +756,31 @@ describe HTTParty::Request do
context "context-encoding" do
before do
@request.options[:format] = :html
@last_response = mock()
@last_response.stub!(:body).and_return('')
@last_response = double()
allow(@last_response).to receive(:body).and_return('')
end
it "should inflate the gzipped body with content-encoding: gzip" do
@last_response.stub!(:[]).with("content-encoding").and_return("gzip")
@request.stub!(:last_response).and_return(@last_response)
Zlib::GzipReader.should_receive(:new).and_return(StringIO.new(''))
@request.last_response.should_receive(:delete).with('content-encoding')
allow(@last_response).to receive(:[]).with("content-encoding").and_return("gzip")
allow(@request).to receive(:last_response).and_return(@last_response)
expect(Zlib::GzipReader).to receive(:new).and_return(StringIO.new(''))
expect(@request.last_response).to receive(:delete).with('content-encoding')
@request.send(:handle_deflation)
end
it "should inflate the gzipped body with content-encoding: x-gzip" do
@last_response.stub!(:[]).with("content-encoding").and_return("x-gzip")
@request.stub!(:last_response).and_return(@last_response)
Zlib::GzipReader.should_receive(:new).and_return(StringIO.new(''))
@request.last_response.should_receive(:delete).with('content-encoding')
allow(@last_response).to receive(:[]).with("content-encoding").and_return("x-gzip")
allow(@request).to receive(:last_response).and_return(@last_response)
expect(Zlib::GzipReader).to receive(:new).and_return(StringIO.new(''))
expect(@request.last_response).to receive(:delete).with('content-encoding')
@request.send(:handle_deflation)
end
it "should inflate the deflated body" do
@last_response.stub!(:[]).with("content-encoding").and_return("deflate")
@request.stub!(:last_response).and_return(@last_response)
Zlib::Inflate.should_receive(:inflate).and_return('')
@request.last_response.should_receive(:delete).with('content-encoding')
allow(@last_response).to receive(:[]).with("content-encoding").and_return("deflate")
allow(@request).to receive(:last_response).and_return(@last_response)
expect(Zlib::Inflate).to receive(:inflate).and_return('')
expect(@request.last_response).to receive(:delete).with('content-encoding')
@request.send(:handle_deflation)
end
end
@ -788,29 +788,29 @@ describe HTTParty::Request do
context "with POST http method" do
it "should raise argument error if query is not a hash" do
lambda {
expect {
HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', format: :xml, query: 'astring').perform
}.should raise_error(ArgumentError)
}.to raise_error(ArgumentError)
end
end
describe "argument validation" do
it "should raise argument error if basic_auth and digest_auth are both present" do
lambda {
expect {
HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', basic_auth: {}, digest_auth: {}).perform
}.should raise_error(ArgumentError, "only one authentication method, :basic_auth or :digest_auth may be used at a time")
}.to raise_error(ArgumentError, "only one authentication method, :basic_auth or :digest_auth may be used at a time")
end
it "should raise argument error if basic_auth is not a hash" do
lambda {
expect {
HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', basic_auth: ["foo", "bar"]).perform
}.should raise_error(ArgumentError, ":basic_auth must be a hash")
}.to raise_error(ArgumentError, ":basic_auth must be a hash")
end
it "should raise argument error if digest_auth is not a hash" do
lambda {
expect {
HTTParty::Request.new(Net::HTTP::Post, 'http://api.foo.com/v1', digest_auth: ["foo", "bar"]).perform
}.should raise_error(ArgumentError, ":digest_auth must be a hash")
}.to raise_error(ArgumentError, ":digest_auth must be a hash")
end
end
end

View file

@ -1,12 +1,12 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
describe HTTParty::Response do
RSpec.describe HTTParty::Response do
before do
@last_modified = Date.new(2010, 1, 15).to_s
@content_length = '1024'
@request_object = HTTParty::Request.new Net::HTTP::Get, '/'
@response_object = Net::HTTPOK.new('1.1', 200, 'OK')
@response_object.stub(body: "{foo:'bar'}")
allow(@response_object).to receive_messages(body: "{foo:'bar'}")
@response_object['last-modified'] = @last_modified
@response_object['content-length'] = @content_length
@parsed_response = lambda { {"foo" => "bar"} }
@ -15,79 +15,79 @@ describe HTTParty::Response do
describe ".underscore" do
it "works with one capitalized word" do
HTTParty::Response.underscore("Accepted").should == "accepted"
expect(HTTParty::Response.underscore("Accepted")).to eq("accepted")
end
it "works with titlecase" do
HTTParty::Response.underscore("BadGateway").should == "bad_gateway"
expect(HTTParty::Response.underscore("BadGateway")).to eq("bad_gateway")
end
it "works with all caps" do
HTTParty::Response.underscore("OK").should == "ok"
expect(HTTParty::Response.underscore("OK")).to eq("ok")
end
end
describe "initialization" do
it "should set the Net::HTTP Response" do
@response.response.should == @response_object
expect(@response.response).to eq(@response_object)
end
it "should set body" do
@response.body.should == @response_object.body
expect(@response.body).to eq(@response_object.body)
end
it "should set code" do
@response.code.should.to_s == @response_object.code
expect(@response.code).to eq(@response_object.code)
end
it "should set code as a Fixnum" do
@response.code.should be_an_instance_of(Fixnum)
expect(@response.code).to be_an_instance_of(Fixnum)
end
end
it "returns response headers" do
response = HTTParty::Response.new(@request_object, @response_object, @parsed_response)
response.headers.should == {'last-modified' => [@last_modified], 'content-length' => [@content_length]}
expect(response.headers).to eq({'last-modified' => [@last_modified], 'content-length' => [@content_length]})
end
it "should send missing methods to delegate" do
response = HTTParty::Response.new(@request_object, @response_object, @parsed_response)
response['foo'].should == 'bar'
expect(response['foo']).to eq('bar')
end
it "response to request" do
response = HTTParty::Response.new(@request_object, @response_object, @parsed_response)
response.respond_to?(:request).should be_true
expect(response.respond_to?(:request)).to be_truthy
end
it "responds to response" do
response = HTTParty::Response.new(@request_object, @response_object, @parsed_response)
response.respond_to?(:response).should be_true
expect(response.respond_to?(:response)).to be_truthy
end
it "responds to body" do
response = HTTParty::Response.new(@request_object, @response_object, @parsed_response)
response.respond_to?(:body).should be_true
expect(response.respond_to?(:body)).to be_truthy
end
it "responds to headers" do
response = HTTParty::Response.new(@request_object, @response_object, @parsed_response)
response.respond_to?(:headers).should be_true
expect(response.respond_to?(:headers)).to be_truthy
end
it "responds to parsed_response" do
response = HTTParty::Response.new(@request_object, @response_object, @parsed_response)
response.respond_to?(:parsed_response).should be_true
expect(response.respond_to?(:parsed_response)).to be_truthy
end
it "responds to anything parsed_response responds to" do
response = HTTParty::Response.new(@request_object, @response_object, @parsed_response)
response.respond_to?(:[]).should be_true
expect(response.respond_to?(:[])).to be_truthy
end
it "should be able to iterate if it is array" do
response = HTTParty::Response.new(@request_object, @response_object, lambda { [{'foo' => 'bar'}, {'foo' => 'baz'}] })
response.size.should == 2
expect(response.size).to eq(2)
expect {
response.each { |item| }
}.to_not raise_error
@ -95,14 +95,14 @@ describe HTTParty::Response do
it "allows headers to be accessed by mixed-case names in hash notation" do
response = HTTParty::Response.new(@request_object, @response_object, @parsed_response)
response.headers['Content-LENGTH'].should == @content_length
expect(response.headers['Content-LENGTH']).to eq(@content_length)
end
it "returns a comma-delimited value when multiple values exist" do
@response_object.add_field 'set-cookie', 'csrf_id=12345; path=/'
@response_object.add_field 'set-cookie', '_github_ses=A123CdE; path=/'
response = HTTParty::Response.new(@request_object, @response_object, @parsed_response)
response.headers['set-cookie'].should == "csrf_id=12345; path=/, _github_ses=A123CdE; path=/"
expect(response.headers['set-cookie']).to eq("csrf_id=12345; path=/, _github_ses=A123CdE; path=/")
end
# Backwards-compatibility - previously, #headers returned a Hash
@ -110,14 +110,14 @@ describe HTTParty::Response do
response = HTTParty::Response.new(@request_object, @response_object, @parsed_response)
hash_methods = {}.methods - response.headers.methods
hash_methods.each do |method_name|
response.headers.respond_to?(method_name).should be_true
expect(response.headers.respond_to?(method_name)).to be_truthy
end
end
describe "semantic methods for response codes" do
def response_mock(klass)
response = klass.new('', '', '')
response.stub(:body)
allow(response).to receive(:body)
response
end
@ -125,31 +125,31 @@ describe HTTParty::Response do
it "is information" do
net_response = response_mock(Net::HTTPInformation)
response = HTTParty::Response.new(@request_object, net_response, '')
response.information?.should be_true
expect(response.information?).to be_truthy
end
it "is success" do
net_response = response_mock(Net::HTTPSuccess)
response = HTTParty::Response.new(@request_object, net_response, '')
response.success?.should be_true
expect(response.success?).to be_truthy
end
it "is redirection" do
net_response = response_mock(Net::HTTPRedirection)
response = HTTParty::Response.new(@request_object, net_response, '')
response.redirection?.should be_true
expect(response.redirection?).to be_truthy
end
it "is client error" do
net_response = response_mock(Net::HTTPClientError)
response = HTTParty::Response.new(@request_object, net_response, '')
response.client_error?.should be_true
expect(response.client_error?).to be_truthy
end
it "is server error" do
net_response = response_mock(Net::HTTPServerError)
response = HTTParty::Response.new(@request_object, net_response, '')
response.server_error?.should be_true
expect(response.server_error?).to be_truthy
end
end
@ -206,7 +206,7 @@ describe HTTParty::Response do
it "responds to #{method}" do
net_response = response_mock(klass)
response = HTTParty::Response.new(@request_object, net_response, '')
response.__send__(method).should be_true
expect(response.__send__(method)).to be_truthy
end
end
end
@ -215,7 +215,7 @@ describe HTTParty::Response do
describe "headers" do
it "can initialize without headers" do
headers = HTTParty::Response::Headers.new
headers.should == {}
expect(headers).to eq({})
end
end
end

View file

@ -1,6 +1,6 @@
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'spec_helper'))
describe HTTParty::Request do
RSpec.describe HTTParty::Request do
context "SSL certificate verification" do
before do
FakeWeb.allow_net_connect = true
@ -11,64 +11,64 @@ describe HTTParty::Request do
end
it "should fail when no trusted CA list is specified, by default" do
lambda do
expect do
ssl_verify_test(nil, nil, "selfsigned.crt")
end.should raise_error OpenSSL::SSL::SSLError
end.to raise_error OpenSSL::SSL::SSLError
end
it "should work when no trusted CA list is specified, when the verify option is set to false" do
ssl_verify_test(nil, nil, "selfsigned.crt", verify: false).should == {'success' => true}
expect(ssl_verify_test(nil, nil, "selfsigned.crt", verify: false)).to include({'success' => true})
end
it "should fail when no trusted CA list is specified, with a bogus hostname, by default" do
lambda do
expect do
ssl_verify_test(nil, nil, "bogushost.crt")
end.should raise_error OpenSSL::SSL::SSLError
end.to raise_error OpenSSL::SSL::SSLError
end
it "should work when no trusted CA list is specified, even with a bogus hostname, when the verify option is set to true" do
ssl_verify_test(nil, nil, "bogushost.crt", verify: false).should == {'success' => true}
expect(ssl_verify_test(nil, nil, "bogushost.crt", verify: false)).to include({'success' => true})
end
it "should work when using ssl_ca_file with a self-signed CA" do
ssl_verify_test(:ssl_ca_file, "selfsigned.crt", "selfsigned.crt").should == {'success' => true}
expect(ssl_verify_test(:ssl_ca_file, "selfsigned.crt", "selfsigned.crt")).to include({'success' => true})
end
it "should work when using ssl_ca_file with a certificate authority" do
ssl_verify_test(:ssl_ca_file, "ca.crt", "server.crt").should == {'success' => true}
expect(ssl_verify_test(:ssl_ca_file, "ca.crt", "server.crt")).to include({'success' => true})
end
it "should work when using ssl_ca_path with a certificate authority" do
http = Net::HTTP.new('www.google.com', 443)
response = stub(Net::HTTPResponse, :[] => '', body: '', to_hash: {})
http.stub(:request).and_return(response)
Net::HTTP.should_receive(:new).with('www.google.com', 443).and_return(http)
http.should_receive(:ca_path=).with('/foo/bar')
response = double(Net::HTTPResponse, :[] => '', body: '', to_hash: {})
allow(http).to receive(:request).and_return(response)
expect(Net::HTTP).to receive(:new).with('www.google.com', 443).and_return(http)
expect(http).to receive(:ca_path=).with('/foo/bar')
HTTParty.get('https://www.google.com', ssl_ca_path: '/foo/bar')
end
it "should fail when using ssl_ca_file and the server uses an unrecognized certificate authority" do
lambda do
expect do
ssl_verify_test(:ssl_ca_file, "ca.crt", "selfsigned.crt")
end.should raise_error(OpenSSL::SSL::SSLError)
end.to raise_error(OpenSSL::SSL::SSLError)
end
it "should fail when using ssl_ca_path and the server uses an unrecognized certificate authority" do
lambda do
expect do
ssl_verify_test(:ssl_ca_path, ".", "selfsigned.crt")
end.should raise_error(OpenSSL::SSL::SSLError)
end.to raise_error(OpenSSL::SSL::SSLError)
end
it "should fail when using ssl_ca_file and the server uses a bogus hostname" do
lambda do
expect do
ssl_verify_test(:ssl_ca_file, "ca.crt", "bogushost.crt")
end.should raise_error(OpenSSL::SSL::SSLError)
end.to raise_error(OpenSSL::SSL::SSLError)
end
it "should fail when using ssl_ca_path and the server uses a bogus hostname" do
lambda do
expect do
ssl_verify_test(:ssl_ca_path, ".", "bogushost.crt")
end.should raise_error(OpenSSL::SSL::SSLError)
end.to raise_error(OpenSSL::SSL::SSLError)
end
end
end

View file

@ -1,6 +1,6 @@
require File.expand_path(File.join(File.dirname(__FILE__), 'spec_helper'))
describe HTTParty do
RSpec.describe HTTParty do
before(:each) do
@klass = Class.new
@klass.instance_eval { include HTTParty }
@ -8,60 +8,60 @@ describe HTTParty do
describe "AllowedFormats deprecated" do
before do
Kernel.stub(:warn)
allow(Kernel).to receive(:warn)
end
it "warns with a deprecation message" do
Kernel.should_receive(:warn).with("Deprecated: Use HTTParty::Parser::SupportedFormats")
expect(Kernel).to receive(:warn).with("Deprecated: Use HTTParty::Parser::SupportedFormats")
HTTParty::AllowedFormats
end
it "returns HTTPart::Parser::SupportedFormats" do
HTTParty::AllowedFormats.should == HTTParty::Parser::SupportedFormats
expect(HTTParty::AllowedFormats).to eq(HTTParty::Parser::SupportedFormats)
end
end
describe "pem" do
it 'should set the pem content' do
@klass.pem 'PEM-CONTENT'
@klass.default_options[:pem].should == 'PEM-CONTENT'
expect(@klass.default_options[:pem]).to eq('PEM-CONTENT')
end
it "should set the password to nil if it's not provided" do
@klass.pem 'PEM-CONTENT'
@klass.default_options[:pem_password].should be_nil
expect(@klass.default_options[:pem_password]).to be_nil
end
it 'should set the password' do
@klass.pem 'PEM-CONTENT', 'PASSWORD'
@klass.default_options[:pem_password].should == 'PASSWORD'
expect(@klass.default_options[:pem_password]).to eq('PASSWORD')
end
end
describe "pkcs12" do
it 'should set the p12 content' do
@klass.pkcs12 'P12-CONTENT', 'PASSWORD'
@klass.default_options[:p12].should == 'P12-CONTENT'
expect(@klass.default_options[:p12]).to eq('P12-CONTENT')
end
it 'should set the password' do
@klass.pkcs12 'P12-CONTENT', 'PASSWORD'
@klass.default_options[:p12_password].should == 'PASSWORD'
expect(@klass.default_options[:p12_password]).to eq('PASSWORD')
end
end
describe 'ssl_version' do
it 'should set the ssl_version content' do
@klass.ssl_version :SSLv3
@klass.default_options[:ssl_version].should == :SSLv3
expect(@klass.default_options[:ssl_version]).to eq(:SSLv3)
end
end
describe 'ciphers' do
it 'should set the ciphers content' do
@klass.default_options[:ciphers].should be_nil
expect(@klass.default_options[:ciphers]).to be_nil
@klass.ciphers 'RC4-SHA'
@klass.default_options[:ciphers].should == 'RC4-SHA'
expect(@klass.default_options[:ciphers]).to eq('RC4-SHA')
end
end
@ -69,15 +69,15 @@ describe HTTParty do
it 'should set the address' do
@klass.http_proxy 'proxy.foo.com', 80
options = @klass.default_options
options[:http_proxyaddr].should == 'proxy.foo.com'
options[:http_proxyport].should == 80
expect(options[:http_proxyaddr]).to eq('proxy.foo.com')
expect(options[:http_proxyport]).to eq(80)
end
it 'should set the proxy user and pass when they are provided' do
@klass.http_proxy 'proxy.foo.com', 80, 'user', 'pass'
options = @klass.default_options
options[:http_proxyuser].should == 'user'
options[:http_proxypass].should == 'pass'
expect(options[:http_proxyuser]).to eq('user')
expect(options[:http_proxypass]).to eq('pass')
end
end
@ -87,71 +87,71 @@ describe HTTParty do
end
it "should have reader" do
@klass.base_uri.should == 'http://api.foo.com/v1'
expect(@klass.base_uri).to eq('http://api.foo.com/v1')
end
it 'should have writer' do
@klass.base_uri('http://api.foobar.com')
@klass.base_uri.should == 'http://api.foobar.com'
expect(@klass.base_uri).to eq('http://api.foobar.com')
end
it 'should not modify the parameter during assignment' do
uri = 'http://api.foobar.com'
@klass.base_uri(uri)
uri.should == 'http://api.foobar.com'
expect(uri).to eq('http://api.foobar.com')
end
end
describe ".disable_rails_query_string_format" do
it "sets the query string normalizer to HTTParty::Request::NON_RAILS_QUERY_STRING_NORMALIZER" do
@klass.disable_rails_query_string_format
@klass.default_options[:query_string_normalizer].should == HTTParty::Request::NON_RAILS_QUERY_STRING_NORMALIZER
expect(@klass.default_options[:query_string_normalizer]).to eq(HTTParty::Request::NON_RAILS_QUERY_STRING_NORMALIZER)
end
end
describe ".normalize_base_uri" do
it "should add http if not present for non ssl requests" do
uri = HTTParty.normalize_base_uri('api.foobar.com')
uri.should == 'http://api.foobar.com'
expect(uri).to eq('http://api.foobar.com')
end
it "should add https if not present for ssl requests" do
uri = HTTParty.normalize_base_uri('api.foo.com/v1:443')
uri.should == 'https://api.foo.com/v1:443'
expect(uri).to eq('https://api.foo.com/v1:443')
end
it "should not remove https for ssl requests" do
uri = HTTParty.normalize_base_uri('https://api.foo.com/v1:443')
uri.should == 'https://api.foo.com/v1:443'
expect(uri).to eq('https://api.foo.com/v1:443')
end
it 'should not modify the parameter' do
uri = 'http://api.foobar.com'
HTTParty.normalize_base_uri(uri)
uri.should == 'http://api.foobar.com'
expect(uri).to eq('http://api.foobar.com')
end
it "should not treat uri's with a port of 4430 as ssl" do
uri = HTTParty.normalize_base_uri('http://api.foo.com:4430/v1')
uri.should == 'http://api.foo.com:4430/v1'
expect(uri).to eq('http://api.foo.com:4430/v1')
end
end
describe "headers" do
def expect_headers(header={})
HTTParty::Request.should_receive(:new) \
expect(HTTParty::Request).to receive(:new) \
.with(anything, anything, hash_including({ headers: header })) \
.and_return(mock("mock response", perform: nil))
.and_return(double("mock response", perform: nil))
end
it "should default to empty hash" do
@klass.headers.should == {}
expect(@klass.headers).to eq({})
end
it "should be able to be updated" do
init_headers = {foo: 'bar', baz: 'spax'}
@klass.headers init_headers
@klass.headers.should == init_headers
expect(@klass.headers).to eq(init_headers)
end
it "uses the class headers when sending a request" do
@ -187,10 +187,10 @@ describe HTTParty do
end
it 'doesnt modify default_options' do
@klass.headers.should == {}
expect(@klass.headers).to eq({})
expect_headers('cookie' => 'type=snickerdoodle')
@klass.get('', cookies: {type: 'snickerdoodle'})
@klass.default_options[:headers].should == {}
expect(@klass.default_options[:headers]).to eq({})
end
it 'adds optional cookies to the optional headers' do
@ -202,21 +202,21 @@ describe HTTParty do
describe "cookies" do
def expect_cookie_header(s)
HTTParty::Request.should_receive(:new) \
expect(HTTParty::Request).to receive(:new) \
.with(anything, anything, hash_including({ headers: { "cookie" => s } })) \
.and_return(mock("mock response", perform: nil))
.and_return(double("mock response", perform: nil))
end
it "should not be in the headers by default" do
HTTParty::Request.stub!(:new).and_return(stub(nil, perform: nil))
allow(HTTParty::Request).to receive(:new).and_return(double(nil, perform: nil))
@klass.get("")
@klass.headers.keys.should_not include("cookie")
expect(@klass.headers.keys).not_to include("cookie")
end
it "should raise an ArgumentError if passed a non-Hash" do
lambda do
expect do
@klass.cookies("nonsense")
end.should raise_error(ArgumentError)
end.to raise_error(ArgumentError)
end
it "should allow a cookie to be specified with a one-off request" do
@ -273,55 +273,55 @@ describe HTTParty do
describe "default params" do
it "should default to empty hash" do
@klass.default_params.should == {}
expect(@klass.default_params).to eq({})
end
it "should be able to be updated" do
new_defaults = {foo: 'bar', baz: 'spax'}
@klass.default_params new_defaults
@klass.default_params.should == new_defaults
expect(@klass.default_params).to eq(new_defaults)
end
end
describe "default timeout" do
it "should default to nil" do
@klass.default_options[:timeout].should == nil
expect(@klass.default_options[:timeout]).to eq(nil)
end
it "should support updating" do
@klass.default_timeout 10
@klass.default_options[:timeout].should == 10
expect(@klass.default_options[:timeout]).to eq(10)
end
it "should support floats" do
@klass.default_timeout 0.5
@klass.default_options[:timeout].should == 0.5
expect(@klass.default_options[:timeout]).to eq(0.5)
end
end
describe "debug_output" do
it "stores the given stream as a default_option" do
@klass.debug_output $stdout
@klass.default_options[:debug_output].should == $stdout
expect(@klass.default_options[:debug_output]).to eq($stdout)
end
it "stores the $stderr stream by default" do
@klass.debug_output
@klass.default_options[:debug_output].should == $stderr
expect(@klass.default_options[:debug_output]).to eq($stderr)
end
end
describe "basic http authentication" do
it "should work" do
@klass.basic_auth 'foobar', 'secret'
@klass.default_options[:basic_auth].should == {username: 'foobar', password: 'secret'}
expect(@klass.default_options[:basic_auth]).to eq({username: 'foobar', password: 'secret'})
end
end
describe "digest http authentication" do
it "should work" do
@klass.digest_auth 'foobar', 'secret'
@klass.default_options[:digest_auth].should == {username: 'foobar', password: 'secret'}
expect(@klass.default_options[:digest_auth]).to eq({username: 'foobar', password: 'secret'})
end
end
@ -338,14 +338,14 @@ describe HTTParty do
it "should set parser options" do
@klass.parser parser
@klass.default_options[:parser].should == parser
expect(@klass.default_options[:parser]).to eq(parser)
end
it "should be able parse response with custom parser" do
@klass.parser parser
FakeWeb.register_uri(:get, 'http://twitter.com/statuses/public_timeline.xml', body: 'tweets')
custom_parsed_response = @klass.get('http://twitter.com/statuses/public_timeline.xml')
custom_parsed_response[:sexy].should == true
expect(custom_parsed_response[:sexy]).to eq(true)
end
it "raises UnsupportedFormat when the parser cannot handle the format" do
@ -362,134 +362,134 @@ describe HTTParty do
expect do
@klass.format :json
@klass.parser lambda {|body, format|}
end.to_not raise_error(HTTParty::UnsupportedFormat)
end.to_not raise_error
end
end
describe "connection_adapter" do
let(:uri) { 'http://google.com/api.json' }
let(:connection_adapter) { mock('CustomConnectionAdapter') }
let(:connection_adapter) { double('CustomConnectionAdapter') }
it "should set the connection_adapter" do
@klass.connection_adapter connection_adapter
@klass.default_options[:connection_adapter].should be connection_adapter
expect(@klass.default_options[:connection_adapter]).to be connection_adapter
end
it "should set the connection_adapter_options when provided" do
options = {foo: :bar}
@klass.connection_adapter connection_adapter, options
@klass.default_options[:connection_adapter_options].should be options
expect(@klass.default_options[:connection_adapter_options]).to be options
end
it "should not set the connection_adapter_options when not provided" do
@klass.connection_adapter connection_adapter
@klass.default_options[:connection_adapter_options].should be_nil
expect(@klass.default_options[:connection_adapter_options]).to be_nil
end
it "should process a request with a connection from the adapter" do
connection_adapter_options = {foo: :bar}
connection_adapter.should_receive(:call) do |u,o|
o[:connection_adapter_options].should == connection_adapter_options
expect(connection_adapter).to receive(:call) { |u,o|
expect(o[:connection_adapter_options]).to eq(connection_adapter_options)
HTTParty::ConnectionAdapter.call(u,o)
end.with(URI.parse(uri), kind_of(Hash))
}.with(URI.parse(uri), kind_of(Hash))
FakeWeb.register_uri(:get, uri, body: 'stuff')
@klass.connection_adapter connection_adapter, connection_adapter_options
@klass.get(uri).should == 'stuff'
expect(@klass.get(uri)).to include('stuff')
end
end
describe "format" do
it "should allow xml" do
@klass.format :xml
@klass.default_options[:format].should == :xml
expect(@klass.default_options[:format]).to eq(:xml)
end
it "should allow csv" do
@klass.format :csv
@klass.default_options[:format].should == :csv
expect(@klass.default_options[:format]).to eq(:csv)
end
it "should allow json" do
@klass.format :json
@klass.default_options[:format].should == :json
expect(@klass.default_options[:format]).to eq(:json)
end
it "should allow plain" do
@klass.format :plain
@klass.default_options[:format].should == :plain
expect(@klass.default_options[:format]).to eq(:plain)
end
it 'should not allow funky format' do
lambda do
expect do
@klass.format :foobar
end.should raise_error(HTTParty::UnsupportedFormat)
end.to raise_error(HTTParty::UnsupportedFormat)
end
it 'should only print each format once with an exception' do
lambda do
expect do
@klass.format :foobar
end.should raise_error(HTTParty::UnsupportedFormat, "':foobar' Must be one of: csv, html, json, plain, xml")
end.to raise_error(HTTParty::UnsupportedFormat, "':foobar' Must be one of: csv, html, json, plain, xml")
end
it 'sets the default parser' do
@klass.default_options[:parser].should be_nil
expect(@klass.default_options[:parser]).to be_nil
@klass.format :json
@klass.default_options[:parser].should == HTTParty::Parser
expect(@klass.default_options[:parser]).to eq(HTTParty::Parser)
end
it 'does not reset parser to the default parser' do
my_parser = lambda {}
@klass.parser my_parser
@klass.format :json
@klass.parser.should == my_parser
expect(@klass.parser).to eq(my_parser)
end
end
describe "#no_follow" do
it "sets no_follow to false by default" do
@klass.no_follow
@klass.default_options[:no_follow].should be_false
expect(@klass.default_options[:no_follow]).to be_falsey
end
it "sets the no_follow option to true" do
@klass.no_follow true
@klass.default_options[:no_follow].should be_true
expect(@klass.default_options[:no_follow]).to be_truthy
end
end
describe "#maintain_method_across_redirects" do
it "sets maintain_method_across_redirects to true by default" do
@klass.maintain_method_across_redirects
@klass.default_options[:maintain_method_across_redirects].should be_true
expect(@klass.default_options[:maintain_method_across_redirects]).to be_truthy
end
it "sets the maintain_method_across_redirects option to false" do
@klass.maintain_method_across_redirects false
@klass.default_options[:maintain_method_across_redirects].should be_false
expect(@klass.default_options[:maintain_method_across_redirects]).to be_falsey
end
end
describe "#resend_on_redirect" do
it "sets resend_on_redirect to true by default" do
@klass.resend_on_redirect
@klass.default_options[:resend_on_redirect].should be_true
expect(@klass.default_options[:resend_on_redirect]).to be_truthy
end
it "sets resend_on_redirect option to false" do
@klass.resend_on_redirect false
@klass.default_options[:resend_on_redirect].should be_false
expect(@klass.default_options[:resend_on_redirect]).to be_falsey
end
end
describe ".follow_redirects" do
it "sets follow redirects to true by default" do
@klass.follow_redirects
@klass.default_options[:follow_redirects].should be_true
expect(@klass.default_options[:follow_redirects]).to be_truthy
end
it "sets the follow_redirects option to false" do
@klass.follow_redirects false
@klass.default_options[:follow_redirects].should be_false
expect(@klass.default_options[:follow_redirects]).to be_falsey
end
end
@ -497,7 +497,7 @@ describe HTTParty do
it "sets the query_string_normalizer option" do
normalizer = proc {}
@klass.query_string_normalizer normalizer
@klass.default_options[:query_string_normalizer].should == normalizer
expect(@klass.default_options[:query_string_normalizer]).to eq(normalizer)
end
end
@ -506,61 +506,61 @@ describe HTTParty do
@request = HTTParty::Request.new(Net::HTTP::Get, 'http://api.foo.com/v1', format: :xml, no_follow: true)
@redirect = stub_response 'first redirect', 302
@redirect['location'] = 'http://foo.com/bar'
HTTParty::Request.stub(new: @request)
allow(HTTParty::Request).to receive_messages(new: @request)
end
it "should fail with redirected GET" do
lambda do
expect do
@error = @klass.get('/foo', no_follow: true)
end.should raise_error(HTTParty::RedirectionTooDeep) {|e| e.response.body.should == 'first redirect'}
end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')}
end
it "should fail with redirected POST" do
lambda do
expect do
@klass.post('/foo', no_follow: true)
end.should raise_error(HTTParty::RedirectionTooDeep) {|e| e.response.body.should == 'first redirect'}
end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')}
end
it "should fail with redirected PATCH" do
lambda do
expect do
@klass.patch('/foo', no_follow: true)
end.should raise_error(HTTParty::RedirectionTooDeep) {|e| e.response.body.should == 'first redirect'}
end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')}
end
it "should fail with redirected DELETE" do
lambda do
expect do
@klass.delete('/foo', no_follow: true)
end.should raise_error(HTTParty::RedirectionTooDeep) {|e| e.response.body.should == 'first redirect'}
end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')}
end
it "should fail with redirected MOVE" do
lambda do
expect do
@klass.move('/foo', no_follow: true)
end.should raise_error(HTTParty::RedirectionTooDeep) {|e| e.response.body.should == 'first redirect'}
end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')}
end
it "should fail with redirected COPY" do
lambda do
expect do
@klass.copy('/foo', no_follow: true)
end.should raise_error(HTTParty::RedirectionTooDeep) {|e| e.response.body.should == 'first redirect'}
end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')}
end
it "should fail with redirected PUT" do
lambda do
expect do
@klass.put('/foo', no_follow: true)
end.should raise_error(HTTParty::RedirectionTooDeep) {|e| e.response.body.should == 'first redirect'}
end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')}
end
it "should fail with redirected HEAD" do
lambda do
expect do
@klass.head('/foo', no_follow: true)
end.should raise_error(HTTParty::RedirectionTooDeep) {|e| e.response.body.should == 'first redirect'}
end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')}
end
it "should fail with redirected OPTIONS" do
lambda do
expect do
@klass.options('/foo', no_follow: true)
end.should raise_error(HTTParty::RedirectionTooDeep) {|e| e.response.body.should == 'first redirect'}
end.to raise_error(HTTParty::RedirectionTooDeep) {|e| expect(e.response.body).to eq('first redirect')}
end
end
@ -580,8 +580,8 @@ describe HTTParty do
end
it "should not run over each others options" do
@klass.default_options.should == { base_uri: 'http://first.com', default_params: { one: 1 } }
@additional_klass.default_options.should == { base_uri: 'http://second.com', default_params: { two: 2 } }
expect(@klass.default_options).to eq({ base_uri: 'http://first.com', default_params: { one: 1 } })
expect(@additional_klass.default_options).to eq({ base_uri: 'http://second.com', default_params: { two: 2 } })
end
end
@ -602,68 +602,68 @@ describe HTTParty do
@child1.default_params joe: "alive"
@child2.default_params joe: "dead"
@child1.default_options.should == { default_params: {joe: "alive"} }
@child2.default_options.should == { default_params: {joe: "dead"} }
expect(@child1.default_options).to eq({ default_params: {joe: "alive"} })
expect(@child2.default_options).to eq({ default_params: {joe: "dead"} })
@parent.default_options.should == { }
expect(@parent.default_options).to eq({ })
end
it "inherits default_options from the superclass" do
@parent.basic_auth 'user', 'password'
@child1.default_options.should == {basic_auth: {username: 'user', password: 'password'}}
expect(@child1.default_options).to eq({basic_auth: {username: 'user', password: 'password'}})
@child1.basic_auth 'u', 'p' # modifying child1 has no effect on child2
@child2.default_options.should == {basic_auth: {username: 'user', password: 'password'}}
expect(@child2.default_options).to eq({basic_auth: {username: 'user', password: 'password'}})
end
it "doesn't modify the parent's default options" do
@parent.basic_auth 'user', 'password'
@child1.basic_auth 'u', 'p'
@child1.default_options.should == {basic_auth: {username: 'u', password: 'p'}}
expect(@child1.default_options).to eq({basic_auth: {username: 'u', password: 'p'}})
@child1.basic_auth 'email', 'token'
@child1.default_options.should == {basic_auth: {username: 'email', password: 'token'}}
expect(@child1.default_options).to eq({basic_auth: {username: 'email', password: 'token'}})
@parent.default_options.should == {basic_auth: {username: 'user', password: 'password'}}
expect(@parent.default_options).to eq({basic_auth: {username: 'user', password: 'password'}})
end
it "doesn't modify hashes in the parent's default options" do
@parent.headers 'Accept' => 'application/json'
@child1.headers 'Accept' => 'application/xml'
@parent.default_options[:headers].should == {'Accept' => 'application/json'}
@child1.default_options[:headers].should == {'Accept' => 'application/xml'}
expect(@parent.default_options[:headers]).to eq({'Accept' => 'application/json'})
expect(@child1.default_options[:headers]).to eq({'Accept' => 'application/xml'})
end
it "works with lambda values" do
@child1.default_options[:imaginary_option] = lambda { "This is a new lambda "}
@child1.default_options[:imaginary_option].should be_a Proc
expect(@child1.default_options[:imaginary_option]).to be_a Proc
end
it 'should dup the proc on the child class' do
imaginary_option = lambda { 2 * 3.14 }
@parent.default_options[:imaginary_option] = imaginary_option
@parent.default_options[:imaginary_option].call.should == imaginary_option.call
expect(@parent.default_options[:imaginary_option].call).to eq(imaginary_option.call)
@child1.default_options[:imaginary_option]
@child1.default_options[:imaginary_option].call.should == imaginary_option.call
@child1.default_options[:imaginary_option].should_not be_equal imaginary_option
expect(@child1.default_options[:imaginary_option].call).to eq(imaginary_option.call)
expect(@child1.default_options[:imaginary_option]).not_to be_equal imaginary_option
end
it "inherits default_cookies from the parent class" do
@parent.cookies 'type' => 'chocolate_chip'
@child1.default_cookies.should == {"type" => "chocolate_chip"}
expect(@child1.default_cookies).to eq({"type" => "chocolate_chip"})
@child1.cookies 'type' => 'snickerdoodle'
@child1.default_cookies.should == {"type" => "snickerdoodle"}
@child2.default_cookies.should == {"type" => "chocolate_chip"}
expect(@child1.default_cookies).to eq({"type" => "snickerdoodle"})
expect(@child2.default_cookies).to eq({"type" => "chocolate_chip"})
end
it "doesn't modify the parent's default cookies" do
@parent.cookies 'type' => 'chocolate_chip'
@child1.cookies 'type' => 'snickerdoodle'
@child1.default_cookies.should == {"type" => "snickerdoodle"}
expect(@child1.default_cookies).to eq({"type" => "snickerdoodle"})
@parent.default_cookies.should == {"type" => "chocolate_chip"}
expect(@parent.default_cookies).to eq({"type" => "chocolate_chip"})
end
end
@ -680,23 +680,25 @@ describe HTTParty do
end
it "continues running the #inherited on the parent" do
child = Class.new(@parent)
child.instance_variable_get(:@grand_parent).should be_true
expect(child.instance_variable_get(:@grand_parent)).to be_truthy
end
end
describe "#get" do
it "should be able to get html" do
stub_http_response_with('google.html')
HTTParty.get('http://www.google.com').should == file_fixture('google.html')
expect(HTTParty.get('http://www.google.com')).to include(file_fixture('google.html'))
end
it "should be able to get chunked html" do
chunks = ["Chunk1", "Chunk2", "Chunk3", "Chunk4"]
stub_chunked_http_response_with(chunks)
HTTParty.get('http://www.google.com') do |fragment|
chunks.should include(fragment)
end.should == chunks.join
expect(
HTTParty.get('http://www.google.com') do |fragment|
expect(chunks).to include(fragment)
end
).to eq(chunks.join)
end
it "should return an empty body if stream_body option is turned on" do
@ -704,16 +706,18 @@ describe HTTParty do
options = {stream_body: true, format: 'html'}
stub_chunked_http_response_with(chunks, options)
HTTParty.get('http://www.google.com', options) do |fragment|
chunks.should include(fragment)
end.should == nil
expect(
HTTParty.get('http://www.google.com', options) do |fragment|
expect(chunks).to include(fragment)
end
).to eq(nil)
end
it "should be able parse response type json automatically" do
stub_http_response_with('twitter.json')
tweets = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
tweets.size.should == 20
tweets.first['user'].should == {
expect(tweets.size).to eq(20)
expect(tweets.first['user']).to eq({
"name" => "Pyk",
"url" => nil,
"id" => "7694602",
@ -723,14 +727,14 @@ describe HTTParty do
"followers_count" => 1,
"location" => "Opera Plaza, California",
"profile_image_url" => "http://static.twitter.com/images/default_profile_normal.png"
}
})
end
it "should be able parse response type xml automatically" do
stub_http_response_with('twitter.xml')
tweets = HTTParty.get('http://twitter.com/statuses/public_timeline.xml')
tweets['statuses'].size.should == 20
tweets['statuses'].first['user'].should == {
expect(tweets['statuses'].size).to eq(20)
expect(tweets['statuses'].first['user']).to eq({
"name" => "Magic 8 Bot",
"url" => nil,
"id" => "17656026",
@ -740,54 +744,54 @@ describe HTTParty do
"followers_count" => "90",
"profile_image_url" => "http://s3.amazonaws.com/twitter_production/profile_images/65565851/8ball_large_normal.jpg",
"location" => nil
}
})
end
it "should be able parse response type csv automatically" do
stub_http_response_with('twitter.csv')
profile = HTTParty.get('http://twitter.com/statuses/profile.csv')
profile.size.should == 2
profile[0].should == ["name","url","id","description","protected","screen_name","followers_count","profile_image_url","location"]
profile[1].should == ["Magic 8 Bot",nil,"17656026","ask me a question","false","magic8bot","90","http://s3.amazonaws.com/twitter_production/profile_images/65565851/8ball_large_normal.jpg",nil]
expect(profile.size).to eq(2)
expect(profile[0]).to eq(["name","url","id","description","protected","screen_name","followers_count","profile_image_url","location"])
expect(profile[1]).to eq(["Magic 8 Bot",nil,"17656026","ask me a question","false","magic8bot","90","http://s3.amazonaws.com/twitter_production/profile_images/65565851/8ball_large_normal.jpg",nil])
end
it "should not get undefined method add_node for nil class for the following xml" do
stub_http_response_with('undefined_method_add_node_for_nil.xml')
result = HTTParty.get('http://foobar.com')
result.should == {"Entities"=>{"href"=>"https://s3-sandbox.parature.com/api/v1/5578/5633/Account", "results"=>"0", "total"=>"0", "page_size"=>"25", "page"=>"1"}}
expect(result).to include({"Entities"=>{"href"=>"https://s3-sandbox.parature.com/api/v1/5578/5633/Account", "results"=>"0", "total"=>"0", "page_size"=>"25", "page"=>"1"}})
end
it "should parse empty response fine" do
stub_http_response_with('empty.xml')
result = HTTParty.get('http://foobar.com')
result.should be_nil
expect(result).to be_nil
end
it "should accept http URIs" do
stub_http_response_with('google.html')
lambda do
expect do
HTTParty.get('http://google.com')
end.should_not raise_error(HTTParty::UnsupportedURIScheme)
end.not_to raise_error
end
it "should accept https URIs" do
stub_http_response_with('google.html')
lambda do
expect do
HTTParty.get('https://google.com')
end.should_not raise_error(HTTParty::UnsupportedURIScheme)
end.not_to raise_error
end
it "should accept webcal URIs" do
stub_http_response_with('google.html')
lambda do
expect do
HTTParty.get('webcal://google.com')
end.should_not raise_error(HTTParty::UnsupportedURIScheme)
end.not_to raise_error
end
it "should raise an InvalidURIError on URIs that can't be parsed at all" do
lambda do
expect do
HTTParty.get("It's the one that says 'Bad URI'")
end.should raise_error(URI::InvalidURIError)
end.to raise_error(URI::InvalidURIError)
end
end
end

View file

@ -1,10 +1,9 @@
require 'simplecov'
$:.push File.expand_path("../lib", __FILE__)
require "simplecov"
SimpleCov.start
require "httparty"
require 'spec/autorun'
require 'fakeweb'
require "fakeweb"
def file_fixture(filename)
open(File.join(File.dirname(__FILE__), 'fixtures', "#{filename.to_s}")).read
@ -12,7 +11,7 @@ end
Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f}
Spec::Runner.configure do |config|
RSpec.configure do |config|
config.include HTTParty::StubResponse
config.include HTTParty::SSLTestHelper
@ -23,15 +22,40 @@ Spec::Runner.configure do |config|
config.after(:suite) do
FakeWeb.allow_net_connect = true
end
config.expect_with :rspec do |expectations|
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.disable_monkey_patching!
config.warnings = true
if config.files_to_run.one?
config.default_formatter = 'doc'
end
config.profile_examples = 10
config.order = :random
Kernel.srand config.seed
end
Spec::Matchers.define :use_ssl do
RSpec::Matchers.define :use_ssl do
match do |connection|
connection.use_ssl?
end
end
Spec::Matchers.define :use_cert_store do |cert_store|
RSpec::Matchers.define :use_cert_store do |cert_store|
match do |connection|
connection.cert_store == cert_store
end

View file

@ -5,38 +5,38 @@ module HTTParty
data = file_fixture(filename)
response = Net::HTTPOK.new("1.1", 200, "Content for you")
response.stub!(:body).and_return(data)
allow(response).to receive(:body).and_return(data)
http_request = HTTParty::Request.new(Net::HTTP::Get, 'http://localhost', format: format)
http_request.stub_chain(:http, :request).and_return(response)
allow(http_request).to receive_message_chain(:http, :request).and_return(response)
HTTParty::Request.should_receive(:new).and_return(http_request)
expect(HTTParty::Request).to receive(:new).and_return(http_request)
end
def stub_chunked_http_response_with(chunks, options={format: "html"})
response = Net::HTTPResponse.new("1.1", 200, nil)
response.stub(:chunked_data).and_return(chunks)
allow(response).to receive(:chunked_data).and_return(chunks)
def response.read_body(&block)
@body || chunked_data.each(&block)
end
http_request = HTTParty::Request.new(Net::HTTP::Get, 'http://localhost', options)
http_request.stub_chain(:http, :request).and_yield(response).and_return(response)
allow(http_request).to receive_message_chain(:http, :request).and_yield(response).and_return(response)
HTTParty::Request.should_receive(:new).and_return(http_request)
expect(HTTParty::Request).to receive(:new).and_return(http_request)
end
def stub_response(body, code = 200)
@request.options[:base_uri] ||= 'http://localhost'
unless defined?(@http) && @http
@http = Net::HTTP.new('localhost', 80)
@request.stub!(:http).and_return(@http)
allow(@request).to receive(:http).and_return(@http)
end
response = Net::HTTPResponse::CODE_TO_OBJ[code.to_s].new("1.1", code, body)
response.stub!(:body).and_return(body)
allow(response).to receive(:body).and_return(body)
@http.stub!(:request).and_return(response)
allow(@http).to receive(:request).and_return(response)
response
end
end