webmock-1.22.6/ 0000755 0000041 0000041 00000000000 12646134265 013272 5 ustar www-data www-data webmock-1.22.6/Rakefile 0000755 0000041 0000041 00000003260 12646134265 014743 0 ustar www-data www-data #!/usr/bin/env rake
require 'bundler'
Bundler::GemHelper.install_tasks
namespace :rvm do
desc 'Run specs against 1.8.6, REE, 1.8.7, 1.9.2 and jRuby'
task :specs do
# JCF: I'd love to be able to use RVM's `rvm {rubies} specs` command but
# the require tests in spec/other_net_http_libs_spec.rb break when doing
# so.
spec_files = Dir[File.dirname(__FILE__) + '/spec/**/*_spec.rb'].join(' ')
sh "rvm 1.8.6@webmock,ree@webmock,1.8.7@webmock,1.9.2@webmock,jruby@webmock exec rspec #{spec_files}"
end
end
require "rspec/core/rake_task"
RSpec::Core::RakeTask.new(:spec) do |t|
t.rspec_opts = ["-c", "-f progress", "-r ./spec/spec_helper.rb"]
t.pattern = 'spec/**/*_spec.rb'
end
RSpec::Core::RakeTask.new(:spec_http_without_webmock) do |t|
t.rspec_opts = ["-c", "-f progress", "-r ./spec/acceptance/net_http/real_net_http_spec.rb"]
t.pattern = 'spec/acceptance/net_http/real_net_http_spec.rb'
end
task :em_http_request_0_x_spec do
sh "EM_HTTP_REQUEST_0_X=true bundle install && EM_HTTP_REQUEST_0_X=true bundle exec rspec spec/acceptance/em_http_request/em_http_request_spec.rb" if RUBY_VERSION <= "1.8.7"
end
require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.test_files = FileList["test/**/*.rb"].exclude("test/test_helper.rb")
test.verbose = false
test.warning = false
end
Rake::TestTask.new(:minitest) do |test|
test.test_files = FileList["minitest/**/*.rb"].exclude("test/test_helper.rb")
test.verbose = false
test.warning = false
end
task :default => [:spec, :spec_http_without_webmock, :test, :minitest]
task :require_ruby_18 do
raise "This must be run on Ruby 1.8" unless RUBY_VERSION =~ /^1\.8/
end
task :release => [:require_ruby_18]
webmock-1.22.6/.gemtest 0000644 0000041 0000041 00000000000 12646134265 014731 0 ustar www-data www-data webmock-1.22.6/Gemfile 0000644 0000041 0000041 00000000372 12646134265 014567 0 ustar www-data www-data source 'http://rubygems.org/'
gemspec
if ENV["EM_HTTP_REQUEST_0_X"]
gem 'em-http-request', '~> 0.3.0'
end
group :development do
gem 'rake'
end
group :test do
gem 'minitest_tu_shim', '1.3.2'
end
platforms :jruby do
gem 'jruby-openssl'
end
webmock-1.22.6/webmock.gemspec 0000644 0000041 0000041 00000004164 12646134265 016273 0 ustar www-data www-data # -*- encoding: utf-8 -*-
$:.push File.expand_path('../lib', __FILE__)
require 'webmock/version'
Gem::Specification.new do |s|
s.name = 'webmock'
s.version = WebMock::VERSION
s.platform = Gem::Platform::RUBY
s.authors = ['Bartosz Blimke']
s.email = ['bartosz.blimke@gmail.com']
s.homepage = 'http://github.com/bblimke/webmock'
s.summary = %q{Library for stubbing HTTP requests in Ruby.}
s.description = %q{WebMock allows stubbing HTTP requests and setting expectations on HTTP requests.}
s.license = "MIT"
s.rubyforge_project = 'webmock'
patron_version = (RUBY_VERSION <= '1.8.7') ? '0.4.18' : '>= 0.4.18'
manticore_version = (RUBY_VERSION) > '1.8.7' ? '>= 0.5.1' : '<= 0.5.1'
s.add_dependency 'addressable', '>= 2.3.6'
s.add_dependency 'crack', '>=0.3.2'
s.add_dependency 'hashdiff'
s.add_development_dependency 'rspec', '>= 3.1.0'
s.add_development_dependency 'httpclient', '>= 2.2.4'
s.add_development_dependency('patron', patron_version) unless RUBY_PLATFORM =~ /java/
s.add_development_dependency 'em-http-request', '>= 1.0.2'
s.add_development_dependency 'http', ((RUBY_VERSION <= '1.9.3') ? '0.7.3' : '>= 0.8.0')
s.add_development_dependency 'em-synchrony', '>= 1.0.0' if RUBY_VERSION >= "1.9"
s.add_development_dependency 'curb', '<= 0.8.6' unless RUBY_PLATFORM =~ /java/
s.add_development_dependency 'typhoeus', '>= 0.5.0' unless RUBY_PLATFORM =~ /java/
s.add_development_dependency('manticore', manticore_version) if RUBY_PLATFORM =~ /java/
s.add_development_dependency 'excon', '>= 0.27.5'
s.add_development_dependency 'minitest', '~> 5.0.0'
s.add_development_dependency 'rdoc', ((RUBY_VERSION == '1.8.6') ? '<= 3.5.0' : '>3.5.0')
s.add_development_dependency 'rack'
s.add_development_dependency "appraisal", "~> 2.0"
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ['lib']
end
webmock-1.22.6/spec/ 0000755 0000041 0000041 00000000000 12646134265 014224 5 ustar www-data www-data webmock-1.22.6/spec/quality_spec.rb 0000644 0000041 0000041 00000005362 12646134265 017261 0 ustar www-data www-data require "spec_helper"
# Borrowed from Bundler
# https://github.com/carlhuda/bundler/blob/1-0-stable/spec/quality_spec.rb
# Portions copyright (c) 2010 Andre Arko
# Portions copyright (c) 2009 Engine Yard
# MIT License
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
describe "The library itself" do
def check_for_tab_characters(filename)
failing_lines = []
File.readlines(filename).each_with_index do |line,number|
failing_lines << number + 1 if line =~ /\t/
end
unless failing_lines.empty?
"#{filename} has tab characters on lines #{failing_lines.join(', ')}"
end
end
def check_for_extra_spaces(filename)
failing_lines = []
File.readlines(filename).each_with_index do |line,number|
next if line =~ /^\s+#.*\s+\n$/
failing_lines << number + 1 if line =~ /\s+\n$/
end
unless failing_lines.empty?
"#{filename} has spaces on the EOL on lines #{failing_lines.join(', ')}"
end
end
RSpec::Matchers.define :be_well_formed do
failure_message do |actual|
actual.join("\n")
end
match do |actual|
actual.empty?
end
end
it "has no malformed whitespace" do
error_messages = []
Dir.chdir(File.expand_path("../..", __FILE__)) do
`git ls-files`.split("\n").each do |filename|
next if filename =~ /\.gitmodules|fixtures/
error_messages << check_for_tab_characters(filename)
error_messages << check_for_extra_spaces(filename)
end
end
expect(error_messages.compact).to be_well_formed
end
it "can still be built" do
Dir.chdir(File.expand_path('../../', __FILE__)) do
`gem build webmock.gemspec`
expect($?).to eq(0)
# clean up the .gem generated
system("rm webmock-#{WebMock.version}.gem")
end
end
end
webmock-1.22.6/spec/spec_helper.rb 0000644 0000041 0000041 00000002776 12646134265 017056 0 ustar www-data www-data require 'rubygems'
require 'httpclient'
unless RUBY_PLATFORM =~ /java/
require 'curb'
require 'patron'
require 'em-http'
require 'typhoeus'
end
if RUBY_PLATFORM =~ /java/
require 'manticore'
end
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'rspec'
require 'webmock/rspec'
require 'support/network_connection'
require 'support/webmock_server'
require 'support/my_rack_app'
CURL_EXAMPLE_OUTPUT_PATH = File.expand_path('../support/example_curl_output.txt', __FILE__)
RSpec.configure do |config|
unless NetworkConnection.is_network_available?
warn("No network connectivity. Only examples which do not make real network connections will run.")
no_network_connection = true
end
if ENV["NO_CONNECTION"] || no_network_connection
config.filter_run_excluding :net_connect => true
end
if RUBY_VERSION <= "1.8.7"
config.filter_run_excluding "ruby>1.9" => true
end
config.filter_run_excluding :without_webmock => true
config.before(:suite) do
WebMockServer.instance.start unless WebMockServer.instance.started
end
config.after(:suite) do
WebMockServer.instance.stop
end
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
end
RSpec::Expectations.configuration.warn_about_potential_false_positives = false
def fail()
raise_error(RSpec::Expectations::ExpectationNotMetError)
end
def fail_with(message)
raise_error(RSpec::Expectations::ExpectationNotMetError, message)
end
webmock-1.22.6/spec/unit/ 0000755 0000041 0000041 00000000000 12646134265 015203 5 ustar www-data www-data webmock-1.22.6/spec/unit/request_body_diff_spec.rb 0000644 0000041 0000041 00000004573 12646134265 022250 0 ustar www-data www-data require 'spec_helper'
RSpec.describe WebMock::RequestBodyDiff do
subject { WebMock::RequestBodyDiff.new(request_signature, request_stub) }
let(:uri) { "http://example.com" }
let(:method) { "GET" }
let(:request_stub) { WebMock::RequestStub.new(method, uri) }
let(:request_signature) { WebMock::RequestSignature.new(method, uri) }
let(:request_stub_body) { { "key" => "value"} }
let(:request_signature_body) { {"key" => "different value"}.to_json }
let(:request_pattern) {
WebMock::RequestPattern.new(
method, uri, {:body => request_stub_body}
)
}
before :each do
request_stub.request_pattern = request_pattern
request_signature.headers = {"Content-Type" => "application/json"}
request_signature.body = request_signature_body
end
describe "#body_diff" do
context "request signature is unparseable json" do
let(:request_signature_body) { "youcan'tparsethis!" }
it "returns an empty hash" do
expect(subject.body_diff).to eq({})
end
end
context "request stub body as unparseable json" do
let(:request_stub_body) { "youcan'tparsethis!" }
it "returns an empty hash" do
expect(subject.body_diff).to eq({})
end
end
context "request stub body pattern is hash" do
let(:request_stub_body) { { "key" => "value"} }
it "generates a diff" do
expect(subject.body_diff).to eq(
[["~", "key", "different value", "value"]]
)
end
end
context "request signature doesn't have json headers" do
before :each do
request_signature.headers = {"Content-Type" => "application/xml"}
end
it "returns an empty hash" do
expect(subject.body_diff).to eq({})
end
end
context "request stub body pattern is a string" do
let(:request_stub_body) { { "key" => "value"}.to_json }
it "generates a diff" do
expect(subject.body_diff).to eq(
[["~", "key", "different value", "value"]]
)
end
end
context "stub request has no request pattern" do
let(:request_signature_body) { nil }
it "returns an empty hash" do
expect(subject.body_diff).to eq({})
end
end
context "stub request has no body pattern" do
let(:request_stub_body) { nil }
it "returns an empty hash" do
expect(subject.body_diff).to eq({})
end
end
end
end
webmock-1.22.6/spec/unit/request_stub_spec.rb 0000644 0000041 0000041 00000016060 12646134265 021272 0 ustar www-data www-data require 'spec_helper'
describe WebMock::RequestStub do
before(:each) do
@request_stub = WebMock::RequestStub.new(:get, "www.example.com")
end
it "should have request pattern with method and uri" do
expect(@request_stub.request_pattern.to_s).to eq("GET http://www.example.com/")
end
it "should have response" do
expect(@request_stub.response).to be_a(WebMock::Response)
end
describe "with" do
it "should assign body to request pattern" do
@request_stub.with(:body => "abc")
expect(@request_stub.request_pattern.to_s).to eq(WebMock::RequestPattern.new(:get, "www.example.com", :body => "abc").to_s)
end
it "should assign normalized headers to request pattern" do
@request_stub.with(:headers => {'A' => 'a'})
expect(@request_stub.request_pattern.to_s).to eq(
WebMock::RequestPattern.new(:get, "www.example.com", :headers => {'A' => 'a'}).to_s
)
end
it "should assign given block to request profile" do
@request_stub.with { |req| req.body == "abc" }
expect(@request_stub.request_pattern.matches?(WebMock::RequestSignature.new(:get, "www.example.com", :body => "abc"))).to be_truthy
end
end
describe "to_return" do
it "should assign response with provided options" do
@request_stub.to_return(:body => "abc", :status => 500)
expect(@request_stub.response.body).to eq("abc")
expect(@request_stub.response.status).to eq([500, ""])
end
it "should assign responses with provided options" do
@request_stub.to_return([{:body => "abc"}, {:body => "def"}])
expect([@request_stub.response.body, @request_stub.response.body]).to eq(["abc", "def"])
end
end
describe "then" do
it "should return stub without any modifications, acting as syntactic sugar" do
expect(@request_stub.then).to eq(@request_stub)
end
end
describe "response" do
it "should return responses in a sequence passed as array" do
@request_stub.to_return([{:body => "abc"}, {:body => "def"}])
expect(@request_stub.response.body).to eq("abc")
expect(@request_stub.response.body).to eq("def")
end
it "should repeat returning last response" do
@request_stub.to_return([{:body => "abc"}, {:body => "def"}])
@request_stub.response
@request_stub.response
expect(@request_stub.response.body).to eq("def")
end
it "should return responses in a sequence passed as comma separated params" do
@request_stub.to_return({:body => "abc"}, {:body => "def"})
expect(@request_stub.response.body).to eq("abc")
expect(@request_stub.response.body).to eq("def")
end
it "should return responses declared in multiple to_return declarations" do
@request_stub.to_return({:body => "abc"}).to_return({:body => "def"})
expect(@request_stub.response.body).to eq("abc")
expect(@request_stub.response.body).to eq("def")
end
end
describe "to_raise" do
it "should assign response with exception to be thrown" do
@request_stub.to_raise(ArgumentError)
expect {
@request_stub.response.raise_error_if_any
}.to raise_error(ArgumentError, "Exception from WebMock")
end
it "should assign sequence of responses with response with exception to be thrown" do
@request_stub.to_return(:body => "abc").then.to_raise(ArgumentError)
expect(@request_stub.response.body).to eq("abc")
expect {
@request_stub.response.raise_error_if_any
}.to raise_error(ArgumentError, "Exception from WebMock")
end
it "should assign a list responses to be thrown in a sequence" do
@request_stub.to_raise(ArgumentError, IndexError)
expect {
@request_stub.response.raise_error_if_any
}.to raise_error(ArgumentError, "Exception from WebMock")
expect {
@request_stub.response.raise_error_if_any
}.to raise_error(IndexError, "Exception from WebMock")
end
it "should raise exceptions declared in multiple to_raise declarations" do
@request_stub.to_raise(ArgumentError).then.to_raise(IndexError)
expect {
@request_stub.response.raise_error_if_any
}.to raise_error(ArgumentError, "Exception from WebMock")
expect {
@request_stub.response.raise_error_if_any
}.to raise_error(IndexError, "Exception from WebMock")
end
end
describe "to_timeout" do
it "should assign response with timeout" do
@request_stub.to_timeout
expect(@request_stub.response.should_timeout).to be_truthy
end
it "should assign sequence of responses with response with timeout" do
@request_stub.to_return(:body => "abc").then.to_timeout
expect(@request_stub.response.body).to eq("abc")
expect(@request_stub.response.should_timeout).to be_truthy
end
it "should allow multiple timeouts to be declared" do
@request_stub.to_timeout.then.to_timeout.then.to_return(:body => "abc")
expect(@request_stub.response.should_timeout).to be_truthy
expect(@request_stub.response.should_timeout).to be_truthy
expect(@request_stub.response.body).to eq("abc")
end
end
describe "times" do
it "should give error if declared before any response declaration is declared" do
expect {
@request_stub.times(3)
}.to raise_error("Invalid WebMock stub declaration. times(N) can be declared only after response declaration.")
end
it "should repeat returning last declared response declared number of times" do
@request_stub.to_return({:body => "abc"}).times(2).then.to_return({:body => "def"})
expect(@request_stub.response.body).to eq("abc")
expect(@request_stub.response.body).to eq("abc")
expect(@request_stub.response.body).to eq("def")
end
it "should repeat raising last declared exception declared number of times" do
@request_stub.to_return({:body => "abc"}).times(2).then.to_return({:body => "def"})
expect(@request_stub.response.body).to eq("abc")
expect(@request_stub.response.body).to eq("abc")
expect(@request_stub.response.body).to eq("def")
end
it "should repeat returning last declared sequence of responses declared number of times" do
@request_stub.to_return({:body => "abc"}, {:body => "def"}).times(2).then.to_return({:body => "ghj"})
expect(@request_stub.response.body).to eq("abc")
expect(@request_stub.response.body).to eq("def")
expect(@request_stub.response.body).to eq("abc")
expect(@request_stub.response.body).to eq("def")
expect(@request_stub.response.body).to eq("ghj")
end
it "should return self" do
expect(@request_stub.to_return({:body => "abc"}).times(1)).to eq(@request_stub)
end
it "should raise error if argument is not integer" do
expect {
@request_stub.to_return({:body => "abc"}).times("not number")
}.to raise_error("times(N) accepts integers >= 1 only")
end
it "should raise error if argument is < 1" do
expect {
@request_stub.to_return({:body => "abc"}).times(0)
}.to raise_error("times(N) accepts integers >= 1 only")
end
end
end
webmock-1.22.6/spec/unit/stub_registry_spec.rb 0000644 0000041 0000041 00000010546 12646134265 021455 0 ustar www-data www-data require 'spec_helper'
describe WebMock::StubRegistry do
before(:each) do
WebMock::StubRegistry.instance.reset!
@request_pattern = WebMock::RequestPattern.new(:get, "www.example.com")
@request_signature = WebMock::RequestSignature.new(:get, "www.example.com")
@request_stub = WebMock::RequestStub.new(:get, "www.example.com")
end
describe "remove_request_stub" do
it "should remove stub from registry" do
WebMock::StubRegistry.instance.register_request_stub(@request_stub)
expect(WebMock::StubRegistry.instance.registered_request?(@request_signature)).to eq(@request_stub)
WebMock::StubRegistry.instance.remove_request_stub(@request_stub)
expect(WebMock::StubRegistry.instance.registered_request?(@request_signature)).to eq(nil)
end
end
describe "reset!" do
before(:each) do
WebMock::StubRegistry.instance.register_request_stub(@request_stub)
end
it "should clean request stubs" do
expect(WebMock::StubRegistry.instance.registered_request?(@request_signature)).to eq(@request_stub)
WebMock::StubRegistry.instance.reset!
expect(WebMock::StubRegistry.instance.registered_request?(@request_signature)).to eq(nil)
end
end
describe "registering and reporting registered requests" do
it "should return registered stub" do
expect(WebMock::StubRegistry.instance.register_request_stub(@request_stub)).to eq(@request_stub)
end
it "should report if request stub is not registered" do
expect(WebMock::StubRegistry.instance.registered_request?(@request_signature)).to eq(nil)
end
it "should register and report registered stub" do
WebMock::StubRegistry.instance.register_request_stub(@request_stub)
expect(WebMock::StubRegistry.instance.registered_request?(@request_signature)).to eq(@request_stub)
end
end
describe "response for request" do
it "should report registered evaluated response for request pattern" do
@request_stub.to_return(:body => "abc")
WebMock::StubRegistry.instance.register_request_stub(@request_stub)
expect(WebMock::StubRegistry.instance.response_for_request(@request_signature)).
to eq(WebMock::Response.new(:body => "abc"))
end
it "should report evaluated response" do
@request_stub.to_return {|request| {:body => request.method.to_s} }
WebMock::StubRegistry.instance.register_request_stub(@request_stub)
response1 = WebMock::StubRegistry.instance.response_for_request(@request_signature)
expect(response1).to eq(WebMock::Response.new(:body => "get"))
end
it "should report clone of the response" do
@request_stub.to_return(:body => lambda{|r| r.method.to_s})
WebMock::StubRegistry.instance.register_request_stub(@request_stub)
response1 = WebMock::StubRegistry.instance.response_for_request(@request_signature)
response2 = WebMock::StubRegistry.instance.response_for_request(@request_signature)
expect(response1).not_to be(response2)
end
it "should report clone of the dynamic response" do
@request_stub.to_return {|request| {:body => request.method.to_s} }
WebMock::StubRegistry.instance.register_request_stub(@request_stub)
response1 = WebMock::StubRegistry.instance.response_for_request(@request_signature)
response2 = WebMock::StubRegistry.instance.response_for_request(@request_signature)
expect(response1).not_to be(response2)
end
it "should report nothing if no response for request is registered" do
expect(WebMock::StubRegistry.instance.response_for_request(@request_signature)).to eq(nil)
end
it "should always return last registered matching response" do
@request_stub1 = WebMock::RequestStub.new(:get, "www.example.com")
@request_stub1.to_return(:body => "abc")
@request_stub2 = WebMock::RequestStub.new(:get, "www.example.com")
@request_stub2.to_return(:body => "def")
@request_stub3 = WebMock::RequestStub.new(:get, "www.example.org")
@request_stub3.to_return(:body => "ghj")
WebMock::StubRegistry.instance.register_request_stub(@request_stub1)
WebMock::StubRegistry.instance.register_request_stub(@request_stub2)
WebMock::StubRegistry.instance.register_request_stub(@request_stub3)
expect(WebMock::StubRegistry.instance.response_for_request(@request_signature)).
to eq(WebMock::Response.new(:body => "def"))
end
end
end
webmock-1.22.6/spec/unit/stub_request_snippet_spec.rb 0000644 0000041 0000041 00000011452 12646134265 023034 0 ustar www-data www-data require 'spec_helper'
describe WebMock::StubRequestSnippet do
describe "to_s" do
describe "GET" do
before(:each) do
@request_signature = WebMock::RequestSignature.new(:get, "www.example.com/?a=b&c=d", :headers => {})
end
it "should print stub request snippet with url with params and method and empty successful response" do
expected = %Q(stub_request(:get, "http://www.example.com/?a=b&c=d").\n to_return(:status => 200, :body => "", :headers => {}))
@request_stub = WebMock::RequestStub.from_request_signature(@request_signature)
expect(WebMock::StubRequestSnippet.new(@request_stub).to_s).to eq(expected)
end
it "should print stub request snippet with body if available" do
@request_signature.body = "abcdef"
expected = %Q(stub_request(:get, "http://www.example.com/?a=b&c=d").)+
"\n with(:body => \"abcdef\")." +
"\n to_return(:status => 200, :body => \"\", :headers => {})"
@request_stub = WebMock::RequestStub.from_request_signature(@request_signature)
expect(WebMock::StubRequestSnippet.new(@request_stub).to_s).to eq(expected)
end
it "should print stub request snippet with multiline body" do
@request_signature.body = "abc\ndef"
expected = %Q(stub_request(:get, "http://www.example.com/?a=b&c=d").)+
"\n with(:body => \"abc\\ndef\")." +
"\n to_return(:status => 200, :body => \"\", :headers => {})"
@request_stub = WebMock::RequestStub.from_request_signature(@request_signature)
expect(WebMock::StubRequestSnippet.new(@request_stub).to_s).to eq(expected)
end
it "should print stub request snippet with headers if any" do
@request_signature.headers = {'B' => 'b', 'A' => 'a'}
expected = 'stub_request(:get, "http://www.example.com/?a=b&c=d").'+
"\n with(:headers => {\'A\'=>\'a\', \'B\'=>\'b\'})." +
"\n to_return(:status => 200, :body => \"\", :headers => {})"
@request_stub = WebMock::RequestStub.from_request_signature(@request_signature)
expect(WebMock::StubRequestSnippet.new(@request_stub).to_s).to eq(expected)
end
it "should print stub request snippet with body and headers" do
@request_signature.body = "abcdef"
@request_signature.headers = {'B' => 'b', 'A' => 'a'}
expected = 'stub_request(:get, "http://www.example.com/?a=b&c=d").'+
"\n with(:body => \"abcdef\",\n :headers => {\'A\'=>\'a\', \'B\'=>\'b\'})." +
"\n to_return(:status => 200, :body => \"\", :headers => {})"
@request_stub = WebMock::RequestStub.from_request_signature(@request_signature)
expect(WebMock::StubRequestSnippet.new(@request_stub).to_s).to eq(expected)
end
it "should not print to_return part if not wanted" do
expected = 'stub_request(:get, "http://www.example.com/").'+
"\n with(:body => \"abcdef\")"
stub = WebMock::RequestStub.new(:get, "www.example.com").with(:body => "abcdef").to_return(:body => "hello")
expect(WebMock::StubRequestSnippet.new(stub).to_s(false)).to eq(expected)
end
end
describe "POST" do
let(:form_body) { 'user%5bfirst_name%5d=Bartosz' }
let(:multipart_form_body) { 'complicated stuff--ABC123--goes here' }
it "should print stub request snippet with body as a hash using rails conventions on form posts" do
@request_signature = WebMock::RequestSignature.new(:post, "www.example.com",
:headers => {'Content-Type' => 'application/x-www-form-urlencoded'},
:body => form_body)
@request_stub = WebMock::RequestStub.from_request_signature(@request_signature)
expected = <<-STUB
stub_request(:post, "http://www.example.com/").
with(:body => {"user"=>{"first_name"=>"Bartosz"}},
:headers => {'Content-Type'=>'application/x-www-form-urlencoded'}).
to_return(:status => 200, :body => \"\", :headers => {})
STUB
expect(WebMock::StubRequestSnippet.new(@request_stub).to_s).to eq(expected.strip)
end
it "should print stub request snippet leaving body as string when not a urlencoded form" do
@request_signature = WebMock::RequestSignature.new(:post, "www.example.com",
:headers => {'Content-Type' => 'multipart/form-data; boundary=ABC123'},
:body => multipart_form_body)
@request_stub = WebMock::RequestStub.from_request_signature(@request_signature)
expected = <<-STUB
stub_request(:post, "http://www.example.com/").
with(:body => "#{multipart_form_body}",
:headers => {'Content-Type'=>'multipart/form-data; boundary=ABC123'}).
to_return(:status => 200, :body => \"\", :headers => {})
STUB
expect(WebMock::StubRequestSnippet.new(@request_stub).to_s).to eq(expected.strip)
end
end
end
end
webmock-1.22.6/spec/unit/rack_response_spec.rb 0000644 0000041 0000041 00000006611 12646134265 021404 0 ustar www-data www-data # encoding: utf-8
require 'spec_helper'
describe WebMock::RackResponse do
before :each do
@rack_response = WebMock::RackResponse.new(MyRackApp)
end
it "should hook up to a rack appliance" do
request = WebMock::RequestSignature.new(:get, 'www.example.com')
response = @rack_response.evaluate(request)
expect(response.status.first).to eq(200)
expect(response.body).to include('This is my root!')
end
it "should behave correctly when the rack response is not a simple array of strings" do
request = WebMock::RequestSignature.new(:get, 'www.example.com/non_array_response')
response = @rack_response.evaluate(request)
expect(response.status.first).to eq(200)
expect(response.body).to include('This is not in an array!')
end
it "should shouldn't blow up when hitting a locked resource twice" do
@locked_rack_response = WebMock::RackResponse.new(MyLockedRackApp)
request = WebMock::RequestSignature.new(:get, 'www.example.com/locked')
@locked_rack_response.evaluate(request)
response2 = @locked_rack_response.evaluate(request)
expect(response2.body).to include('Single threaded response.')
expect(response2.status.first).to eq(200)
end
it "should send along params" do
request = WebMock::RequestSignature.new(:get, 'www.example.com/greet?name=Johnny')
response = @rack_response.evaluate(request)
expect(response.status.first).to eq(200)
expect(response.body).to include('Hello, Johnny')
end
it "should send along POST params" do
request = WebMock::RequestSignature.new(:post, 'www.example.com/greet',
:body => 'name=Jimmy'
)
response = @rack_response.evaluate(request)
expect(response.body).to include('Good to meet you, Jimmy!')
end
it "should send params with proper content length if params have non-ascii symbols" do
request = WebMock::RequestSignature.new(:post, 'www.example.com/greet',
:body => 'name=Олег'
)
response = @rack_response.evaluate(request)
expect(response.body).to include('Good to meet you, Олег!')
end
describe 'rack error output' do
before :each do
@original_stderr = $stderr
$stderr = StringIO.new
end
after :each do
$stderr = @original_stderr
end
it 'should behave correctly when an app uses rack.errors' do
request = WebMock::RequestSignature.new(:get, 'www.example.com/error')
expect { @rack_response.evaluate(request) }.to_not raise_error
expect($stderr.length).to_not eq 0
end
end
describe 'basic auth request' do
before :each do
@rack_response_with_basic_auth = WebMock::RackResponse.new(
Rack::Auth::Basic.new(MyRackApp) do |username, password|
username == 'username' && password == 'password'
end
)
end
it 'should be failure when wrong credentials' do
request = WebMock::RequestSignature.new(:get, 'foo:bar@www.example.com')
response = @rack_response_with_basic_auth.evaluate(request)
expect(response.status.first).to eq(401)
expect(response.body).not_to include('This is my root!')
end
it 'should be success when valid credentials' do
request = WebMock::RequestSignature.new(:get, 'username:password@www.example.com')
response = @rack_response_with_basic_auth.evaluate(request)
expect(response.status.first).to eq(200)
expect(response.body).to include('This is my root!')
end
end
end
webmock-1.22.6/spec/unit/errors_spec.rb 0000644 0000041 0000041 00000014533 12646134265 020064 0 ustar www-data www-data require 'spec_helper'
describe "errors" do
describe WebMock::NetConnectNotAllowedError do
describe "message" do
it "should have message with request signature and snippet" do
allow(WebMock::RequestStub).to receive(:from_request_signature).and_return(request_stub)
allow(WebMock::StubRequestSnippet).to receive(:new).
with(request_stub).and_return(stub_result)
expected = \
"Real HTTP connections are disabled. Unregistered request: #{request_signature}" \
"\n\nYou can stub this request with the following snippet:" \
"\n\n#{stub_result}" \
"\n\n============================================================"
expect(WebMock::NetConnectNotAllowedError.new(request_signature).message).to eq(expected)
end
it "should have message with registered stubs if available" do
allow(WebMock::StubRegistry.instance).to receive(:request_stubs).and_return([request_stub])
allow(WebMock::RequestStub).to receive(:from_request_signature).and_return(request_stub)
allow(WebMock::StubRequestSnippet).to receive(:new).
with(request_stub).and_return(stub_result)
allow_any_instance_of(WebMock::RequestBodyDiff).to receive(:body_diff).and_return({})
expected = \
"Real HTTP connections are disabled. Unregistered request: #{request_signature}" \
"\n\nYou can stub this request with the following snippet:" \
"\n\n#{stub_result}" \
"\n\nregistered request stubs:" \
"\n\n#{stub_result}" \
"\n\n============================================================"
expect(WebMock::NetConnectNotAllowedError.new(request_signature).message).to eq(expected)
end
it "should not be caught by a rescue block without arguments" do
allow(WebMock::RequestStub).to receive(:from_request_signature).and_return(request_stub)
allow(WebMock::StubRequestSnippet).to receive(:new).
with(request_stub).and_return(stub_result)
exception = WebMock::NetConnectNotAllowedError.new(request_signature)
expect do
begin
raise exception
rescue
raise "exception should not be caught"
end
end.to raise_exception exception
end
it "should print body diff if available" do
allow(WebMock::StubRegistry.instance).to receive(:request_stubs).and_return([request_stub])
allow(WebMock::RequestStub).to receive(:from_request_signature).and_return(request_stub)
allow(WebMock::StubRequestSnippet).to receive(:new).
with(request_stub).and_return(stub_result)
allow_any_instance_of(WebMock::RequestBodyDiff).to receive(:body_diff).and_return(body_diff)
expected = \
"Real HTTP connections are disabled. Unregistered request: #{request_signature}" \
"\n\nYou can stub this request with the following snippet:" \
"\n\n#{stub_result}" \
"\n\nregistered request stubs:" \
"\n\n#{stub_result}" \
"\n\nBody diff:\n [[\"+\", \"test\", \"test2\"], [\"-\", \"test3\"], [\"~\", \"test5\", \"test6\"]]" \
"\n\n\n============================================================"
expect(WebMock::NetConnectNotAllowedError.new(request_signature).message).to eq(expected)
end
context "WebMock.show_body_diff? is false" do
before do
WebMock.hide_body_diff!
end
it "should not show body diff" do
allow(WebMock::StubRegistry.instance).to receive(:request_stubs).and_return([request_stub])
allow(WebMock::RequestStub).to receive(:from_request_signature).and_return(request_stub)
allow(WebMock::StubRequestSnippet).to receive(:new).
with(request_stub).and_return(stub_result)
expect_any_instance_of(WebMock::RequestBodyDiff).to_not receive(:body_diff)
expected = \
"Real HTTP connections are disabled. Unregistered request: #{request_signature}" \
"\n\nYou can stub this request with the following snippet:" \
"\n\n#{stub_result}" \
"\n\nregistered request stubs:" \
"\n\n#{stub_result}" \
"\n\n============================================================"
expect(WebMock::NetConnectNotAllowedError.new(request_signature).message).to eq(expected)
end
end
context "WebMock.show_stubbing_instructions? is false" do
before do
WebMock.hide_stubbing_instructions!
end
it "should have message with request signature and snippet" do
allow(WebMock::RequestStub).to receive(:from_request_signature).and_return(request_stub)
allow(WebMock::StubRequestSnippet).to receive(:new).
with(request_stub).and_return(stub_result)
expected = \
"Real HTTP connections are disabled. Unregistered request: #{request_signature}" \
"\n\n============================================================"
expect(WebMock::NetConnectNotAllowedError.new(request_signature).message).to eq(expected)
end
it "should have message with registered stubs if available" do
allow(WebMock::StubRegistry.instance).to receive(:request_stubs).and_return([request_stub])
allow(WebMock::RequestStub).to receive(:from_request_signature).and_return(request_stub)
allow(WebMock::StubRequestSnippet).to receive(:new).
with(request_stub).and_return(stub_result)
allow(request_stub).to receive(:request_pattern).and_return(body_pattern)
expected = \
"Real HTTP connections are disabled. Unregistered request: #{request_signature}" \
"\n\nregistered request stubs:" \
"\n\n#{stub_result}" \
"\n\n============================================================"
expect(WebMock::NetConnectNotAllowedError.new(request_signature).message).to eq(expected)
end
end
end
let(:request_signature) { double(:request_signature, :to_s => rand(10**20).to_s) }
let(:stub_result) { double(:stub_result, :to_s => rand(10**20).to_s) }
let(:request_stub) { double(:request_stub) }
let(:body_pattern) { double(:body_pattern, :body_pattern => nil)}
let(:body_diff) { [["+", "test", "test2"], ["-", "test3"], ["~", "test5", "test6"]] }
end
end
webmock-1.22.6/spec/unit/http_lib_adapters/ 0000755 0000041 0000041 00000000000 12646134265 020673 5 ustar www-data www-data webmock-1.22.6/spec/unit/http_lib_adapters/http_lib_adapter_spec.rb 0000644 0000041 0000041 00000000544 12646134265 025542 0 ustar www-data www-data require 'spec_helper'
describe WebMock::HttpLibAdapter do
describe "adapter_for" do
it "should add adapter to adapter registry" do
class MyAdapter < WebMock::HttpLibAdapter; end
expect(WebMock::HttpLibAdapterRegistry.instance).
to receive(:register).with(:my_lib, MyAdapter)
MyAdapter.adapter_for(:my_lib)
end
end
end webmock-1.22.6/spec/unit/http_lib_adapters/http_lib_adapter_registry_spec.rb 0000644 0000041 0000041 00000001057 12646134265 027472 0 ustar www-data www-data require 'spec_helper'
describe WebMock::HttpLibAdapterRegistry do
describe "each_adapter" do
it "should yield block over each adapter" do
class MyAdapter < WebMock::HttpLibAdapter; end
WebMock::HttpLibAdapterRegistry.instance.register(:my_lib, MyAdapter)
adapters = []
WebMock::HttpLibAdapterRegistry.instance.each_adapter {|n,a|
adapters << [n, a]
}
expect(adapters).to include([:my_lib, MyAdapter])
WebMock::HttpLibAdapterRegistry.instance.
http_lib_adapters.delete(:my_lib)
end
end
end webmock-1.22.6/spec/unit/api_spec.rb 0000644 0000041 0000041 00000004332 12646134265 017315 0 ustar www-data www-data require 'spec_helper'
describe WebMock::API do
describe '#hash_including' do
subject { klass.new.hash_including(args) }
let(:args) { {:data => :one} }
context 'when mixed into a class that does not define `hash_including`' do
let(:klass) do
Class.new do
include WebMock::API
end
end
it 'uses WebMock::Matchers::HashIncludingMatcher' do
expect(subject).to be_a(WebMock::Matchers::HashIncludingMatcher)
end
# by testing equality for HashIncludingMatcher (which stringifies the passed hash) we are
# testing HashIncludingMatcher.initialize behavior as well
context "when args correspond to an hash" do
it "creates 'HashIncludingMatcher'" do
expect(subject).to eq("data" => :one)
end
end
context "when args are one or many keys" do
subject {klass.new.hash_including(:foo, :bar)}
let(:anything) { WebMock::Matchers::AnyArgMatcher.new(nil) }
it "creates 'HashIncludingMatcher' with keys anythingized" do
expect(subject).to eq("foo" => anything, "bar" => anything )
end
end
context "when args are both keys and key/value pairs" do
subject {klass.new.hash_including(:foo, :bar, :data => :one)}
let(:anything) { WebMock::Matchers::AnyArgMatcher.new(nil) }
it "creates 'HashIncludingMatcher' with keys anythingized" do
expect(subject).to eq("foo" => anything, "bar" => anything, "data" => :one)
end
end
context "when args are an emtpy hash" do
subject {klass.new.hash_including({})}
it "creates 'HashIncludingMatcher' with an empty hash" do
expect(subject).to eq({})
end
end
end
context 'when mixed into a class with a parent that defines `hash_including`' do
subject {klass.new.hash_including(*args)}
let(:args) { %w(:foo, :bar, {:data => :one}) }
let(:klass) do
Class.new(
Class.new do
def hash_including(*args)
args
end
end
) { include WebMock::API }
end
it 'uses super and passes the args untampered' do
expect(subject).to eq(args)
end
end
end
end webmock-1.22.6/spec/unit/request_execution_verifier_spec.rb 0000644 0000041 0000041 00000021015 12646134265 024207 0 ustar www-data www-data require 'spec_helper'
describe WebMock::RequestExecutionVerifier do
before(:each) do
@verifier = WebMock::RequestExecutionVerifier.new
@request_pattern = double(WebMock::RequestPattern, :to_s => "www.example.com")
@verifier.request_pattern = @request_pattern
allow(WebMock::RequestRegistry.instance).to receive(:to_s).and_return("executed requests")
@executed_requests_info = "\n\nThe following requests were made:\n\nexecuted requests\n" + "="*60
end
describe "description" do
it "reports the description" do
@verifier.expected_times_executed = 2
expect(@verifier.description).to eq "request www.example.com 2 times"
end
it "reports description correctly when expectation is 1 time" do
@verifier.expected_times_executed = 1
expect(@verifier.description).to eq "request www.example.com 1 time"
end
context "at_least_times_executed is set" do
it "reports description correctly when expectation at least 2 times" do
@verifier.at_least_times_executed = 2
expect(@verifier.description).to eq "request www.example.com at least 2 times"
end
it "reports description correctly when expectation is at least 3 times" do
@verifier.at_least_times_executed = 3
expect(@verifier.description).to eq "request www.example.com at least 3 times"
end
end
context "at_most_times_executed is set" do
it "reports description correctly when expectation is at most 2 times" do
@verifier.at_most_times_executed = 2
expect(@verifier.description).to eq "request www.example.com at most 2 times"
end
it "reports description correctly when expectation is at most 1 time" do
@verifier.at_most_times_executed = 1
expect(@verifier.description).to eq "request www.example.com at most 1 time"
end
end
end
describe "failure message" do
it "reports the failure message" do
@verifier.times_executed = 0
@verifier.expected_times_executed = 2
expected_text = "The request www.example.com was expected to execute 2 times but it executed 0 times"
expected_text << @executed_requests_info
expect(@verifier.failure_message).to eq(expected_text)
end
it "reports failure message correctly when executed times is one" do
@verifier.times_executed = 1
@verifier.expected_times_executed = 1
expected_text = "The request www.example.com was expected to execute 1 time but it executed 1 time"
expected_text << @executed_requests_info
expect(@verifier.failure_message).to eq(expected_text)
end
context "at_least_times_executed is set" do
it "reports failure message correctly when executed times is one" do
@verifier.times_executed = 1
@verifier.at_least_times_executed = 2
expected_text = "The request www.example.com was expected to execute at least 2 times but it executed 1 time"
expected_text << @executed_requests_info
expect(@verifier.failure_message).to eq(expected_text)
end
it "reports failure message correctly when executed times is two" do
@verifier.times_executed = 2
@verifier.at_least_times_executed = 3
expected_text = "The request www.example.com was expected to execute at least 3 times but it executed 2 times"
expected_text << @executed_requests_info
expect(@verifier.failure_message).to eq(expected_text)
end
end
context "at_most_times_executed is set" do
it "reports failure message correctly when executed times is three" do
@verifier.times_executed = 3
@verifier.at_most_times_executed = 2
expected_text = "The request www.example.com was expected to execute at most 2 times but it executed 3 times"
expected_text << @executed_requests_info
expect(@verifier.failure_message).to eq(expected_text)
end
it "reports failure message correctly when executed times is two" do
@verifier.times_executed = 2
@verifier.at_most_times_executed = 1
expected_text = "The request www.example.com was expected to execute at most 1 time but it executed 2 times"
expected_text << @executed_requests_info
expect(@verifier.failure_message).to eq(expected_text)
end
end
end
describe "negative failure message" do
it "reports failure message if it executed number of times specified" do
@verifier.times_executed = 2
@verifier.expected_times_executed = 2
expected_text = "The request www.example.com was not expected to execute 2 times but it executed 2 times"
expected_text << @executed_requests_info
expect(@verifier.failure_message_when_negated).to eq(expected_text)
end
it "reports failure message when not expected request but it executed" do
@verifier.times_executed = 1
expected_text = "The request www.example.com was not expected to execute but it executed 1 time"
expected_text << @executed_requests_info
expect(@verifier.failure_message_when_negated).to eq(expected_text)
end
context "at_least_times_executed is set" do
it "reports failure message correctly when executed times is one" do
@verifier.times_executed = 3
@verifier.at_least_times_executed = 2
expected_text = "The request www.example.com was not expected to execute at least 2 times but it executed 3 times"
expected_text << @executed_requests_info
expect(@verifier.failure_message_when_negated).to eq(expected_text)
end
it "reports failure message correctly when executed times is two" do
@verifier.times_executed = 2
@verifier.at_least_times_executed = 2
expected_text = "The request www.example.com was not expected to execute at least 2 times but it executed 2 times"
expected_text << @executed_requests_info
expect(@verifier.failure_message_when_negated).to eq(expected_text)
end
end
context "at_most_times_executed is set" do
it "reports failure message correctly when executed times is three" do
@verifier.times_executed = 2
@verifier.at_most_times_executed = 3
expected_text = "The request www.example.com was not expected to execute at most 3 times but it executed 2 times"
expected_text << @executed_requests_info
expect(@verifier.failure_message_when_negated).to eq(expected_text)
end
it "reports failure message correctly when executed times is one" do
@verifier.times_executed = 1
@verifier.at_most_times_executed = 2
expected_text = "The request www.example.com was not expected to execute at most 2 times but it executed 1 time"
expected_text << @executed_requests_info
expect(@verifier.failure_message_when_negated).to eq(expected_text)
end
end
end
describe "matches?" do
it "succeeds if request was executed expected number of times" do
expect(WebMock::RequestRegistry.instance).
to receive(:times_executed).with(@request_pattern).and_return(10)
@verifier.expected_times_executed = 10
expect(@verifier.matches?).to be_truthy
end
it "fails if request was not executed expected number of times" do
expect(WebMock::RequestRegistry.instance).
to receive(:times_executed).with(@request_pattern).and_return(10)
@verifier.expected_times_executed = 5
expect(@verifier.matches?).to be_falsey
end
end
describe "does_not_match?" do
it "fails if request executed expected number of times" do
expect(WebMock::RequestRegistry.instance).
to receive(:times_executed).with(@request_pattern).and_return(10)
@verifier.expected_times_executed = 10
expect(@verifier.does_not_match?).to be_falsey
end
it "succeeds if request was not executed at all and expected number of times was not set" do
expect(WebMock::RequestRegistry.instance).
to receive(:times_executed).with(@request_pattern).and_return(0)
expect(@verifier.does_not_match?).to be_truthy
end
it "fails if request was executed and expected number of times was not set" do
expect(WebMock::RequestRegistry.instance).
to receive(:times_executed).with(@request_pattern).and_return(1)
expect(@verifier.does_not_match?).to be_falsey
end
it "succeeds if request was not executed expected number of times" do
expect(WebMock::RequestRegistry.instance).
to receive(:times_executed).with(@request_pattern).and_return(10)
@verifier.expected_times_executed = 5
expect(@verifier.does_not_match?).to be_truthy
end
end
end
webmock-1.22.6/spec/unit/request_pattern_spec.rb 0000644 0000041 0000041 00000074365 12646134265 022006 0 ustar www-data www-data require 'spec_helper'
describe WebMock::RequestPattern do
describe "describing itself" do
it "should report string describing itself" do
expect(WebMock::RequestPattern.new(:get, "www.example.com",
:body => "abc", :headers => {'A' => 'a', 'B' => 'b'}).to_s).to eq(
"GET http://www.example.com/ with body \"abc\" with headers {'A'=>'a', 'B'=>'b'}"
)
end
it "should report string describing itself with block" do
expect(WebMock::RequestPattern.new(:get, "www.example.com",
:body => "abc", :headers => {'A' => 'a', 'B' => 'b'}).with {|req| true}.to_s).to eq(
"GET http://www.example.com/ with body \"abc\" with headers {'A'=>'a', 'B'=>'b'} with given block"
)
end
it "should report string describing itself with query params" do
expect(WebMock::RequestPattern.new(:get, /.*example.*/, :query => {'a' => ['b', 'c']}).to_s).to eq(
"GET /.*example.*/ with query params {\"a\"=>[\"b\", \"c\"]}"
)
end
it "should report string describing itself with query params as hash including matcher" do
expect(WebMock::RequestPattern.new(:get, /.*example.*/,
:query => WebMock::Matchers::HashIncludingMatcher.new({'a' => ['b', 'c']})).to_s).to eq(
"GET /.*example.*/ with query params hash_including({\"a\"=>[\"b\", \"c\"]})"
)
end
it "should report string describing itself with body as hash including matcher" do
expect(WebMock::RequestPattern.new(:get, /.*example.*/,
:body => WebMock::Matchers::HashIncludingMatcher.new({'a' => ['b', 'c']})).to_s).to eq(
"GET /.*example.*/ with body hash_including({\"a\"=>[\"b\", \"c\"]})"
)
end
end
describe "with" do
before(:each) do
@request_pattern =WebMock::RequestPattern.new(:get, "www.example.com")
end
it "should have assigned body pattern" do
@request_pattern.with(:body => "abc")
expect(@request_pattern.to_s).to eq(WebMock::RequestPattern.new(:get, "www.example.com", :body => "abc").to_s)
end
it "should have assigned normalized headers pattern" do
@request_pattern.with(:headers => {'A' => 'a'})
expect(@request_pattern.to_s).to eq(WebMock::RequestPattern.new(:get, "www.example.com", :headers => {'A' => 'a'}).to_s)
end
it "should raise an error if options passed to `with` are invalid" do
expect { @request_pattern.with(:foo => "bar") }.to raise_error('Unknown key: "foo". Valid keys are: "body", "headers", "query"')
end
it "should raise an error if neither options or block is provided" do
expect { @request_pattern.with() }.to raise_error('#with method invoked with no arguments. Either options hash or block must be specified.')
end
end
class WebMock::RequestPattern
def match(request_signature)
self.matches?(request_signature)
end
end
describe "when matching" do
it "should match if uri matches and method matches" do
expect(WebMock::RequestPattern.new(:get, "www.example.com")).
to match(WebMock::RequestSignature.new(:get, "www.example.com"))
end
it "should match if uri matches and method pattern is any" do
expect(WebMock::RequestPattern.new(:any, "www.example.com")).
to match(WebMock::RequestSignature.new(:get, "www.example.com"))
end
it "should not match if request has different method" do
expect(WebMock::RequestPattern.new(:post, "www.example.com")).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com"))
end
it "should match if uri matches request uri" do
expect(WebMock::RequestPattern.new(:get, "www.example.com")).
to match(WebMock::RequestSignature.new(:get, "www.example.com"))
end
it "should match if request has unescaped uri" do
expect(WebMock::RequestPattern.new(:get, "www.example.com/my%20path")).
to match(WebMock::RequestSignature.new(:get, "www.example.com/my path"))
end
it "should match if request has escaped uri" do
expect(WebMock::RequestPattern.new(:get, "www.example.com/my path")).
to match(WebMock::RequestSignature.new(:get, "www.example.com/my%20path"))
end
it "should match if uri regexp pattern matches unescaped form of request uri" do
expect(WebMock::RequestPattern.new(:get, /.*my path.*/)).
to match(WebMock::RequestSignature.new(:get, "www.example.com/my%20path"))
end
it "should match if uri regexp pattern matches request uri" do
expect(WebMock::RequestPattern.new(:get, /.*example.*/)).
to match(WebMock::RequestSignature.new(:get, "www.example.com"))
end
it "should match if uri Addressable::Template pattern matches unescaped form of request uri" do
expect(WebMock::RequestPattern.new(:get, Addressable::Template.new("www.example.com/{any_path}"))).
to match(WebMock::RequestSignature.new(:get, "www.example.com/my%20path"))
end
it "should match if uri Addressable::Template pattern matches request uri" do
expect(WebMock::RequestPattern.new(:get, Addressable::Template.new("www.example.com"))).
to match(WebMock::RequestSignature.new(:get, "www.example.com"))
end
it "should match for uris with same parameters as pattern" do
expect(WebMock::RequestPattern.new(:get, "www.example.com?a=1&b=2")).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a=1&b=2"))
end
it "should not match for uris with different parameters" do
expect(WebMock::RequestPattern.new(:get, "www.example.com?a=1&b=2")).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com?a=2&b=1"))
end
it "should match for uri parameters in different order" do
expect(WebMock::RequestPattern.new(:get, "www.example.com?b=2&a=1")).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a=1&b=2"))
end
describe "when parameters are escaped" do
it "should match if uri pattern has escaped parameters and request has unescaped parameters" do
expect(WebMock::RequestPattern.new(:get, "www.example.com/?a=a%20b")).
to match(WebMock::RequestSignature.new(:get, "www.example.com/?a=a b"))
end
it "should match if uri pattern has unescaped parameters and request has escaped parameters" do
expect(WebMock::RequestPattern.new(:get, "www.example.com/?a=a b")).
to match(WebMock::RequestSignature.new(:get, "www.example.com/?a=a%20b"))
end
it "should match if uri regexp pattern matches uri with unescaped parameters and request has escaped parameters" do
expect(WebMock::RequestPattern.new(:get, /.*a=a b.*/)).
to match(WebMock::RequestSignature.new(:get, "www.example.com/?a=a%20b"))
end
it "should match if uri regexp pattern matches uri with escaped parameters and request has unescaped parameters" do
expect(WebMock::RequestPattern.new(:get, /.*a=a%20b.*/)).
to match(WebMock::RequestSignature.new(:get, "www.example.com/?a=a b"))
end
it "should match if uri Addressable::Template pattern matches uri without parameter value and request has escaped parameters" do
expect(WebMock::RequestPattern.new(:get, Addressable::Template.new("www.example.com/{?a}"))).
to match(WebMock::RequestSignature.new(:get, "www.example.com/?a=a%20b"))
end
it "should match if uri Addressable::Template pattern matches uri without parameter value and request has unescaped parameters" do
expect(WebMock::RequestPattern.new(:get, Addressable::Template.new("www.example.com/{?a}"))).
to match(WebMock::RequestSignature.new(:get, "www.example.com/?a=a b"))
end
it "should match if uri Addressable::Template pattern matches uri with unescaped parameter value and request has unescaped parameters" do
expect(WebMock::RequestPattern.new(:get, Addressable::Template.new("www.example.com/?a=a b"))).
to match(WebMock::RequestSignature.new(:get, "www.example.com/?a=a b"))
end
it "should match if uri Addressable::Template pattern matches uri with escaped parameter value and request has escaped parameters" do
expect(WebMock::RequestPattern.new(:get, Addressable::Template.new("www.example.com/?a=a%20b"))).
to match(WebMock::RequestSignature.new(:get, "www.example.com/?a=a%20b"))
end
end
describe "when matching requests on query params" do
describe "when uri is described as regexp" do
it "should match request query params" do
expect(WebMock::RequestPattern.new(:get, /.*example.*/, :query => {"a" => ["b", "c"]})).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c"))
end
it "should match request query params if params don't match" do
expect(WebMock::RequestPattern.new(:get, /.*example.*/, :query => {"x" => ["b", "c"]})).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c"))
end
it "should match when query params are declared as HashIncluding matcher matching params" do
expect(WebMock::RequestPattern.new(:get, /.*example.*/,
:query => WebMock::Matchers::HashIncludingMatcher.new({"a" => ["b", "c"]}))).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c&b=1"))
end
it "should not match when query params are declared as HashIncluding matcher not matching params" do
expect(WebMock::RequestPattern.new(:get, /.*example.*/,
:query => WebMock::Matchers::HashIncludingMatcher.new({"x" => ["b", "c"]}))).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c&b=1"))
end
it "should match when query params are declared as RSpec HashIncluding matcher matching params" do
expect(WebMock::RequestPattern.new(:get, /.*example.*/,
:query => RSpec::Mocks::ArgumentMatchers::HashIncludingMatcher.new({"a" => ["b", "c"]}))).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c&b=1"))
end
it "should not match when query params are declared as RSpec HashIncluding matcher not matching params" do
expect(WebMock::RequestPattern.new(:get, /.*example.*/,
:query => RSpec::Mocks::ArgumentMatchers::HashIncludingMatcher.new({"a" => ["b", "d"]}))).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c&b=1"))
end
end
describe "when uri is described as Addressable::Template" do
it "should raise error if query params are specified" do
expect(WebMock::RequestPattern.new(:get, Addressable::Template.new("www.example.com"), :query => {"a" => ["b", "c"]})).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c"))
end
it "should match request query params if params don't match" do
expect(WebMock::RequestPattern.new(:get, Addressable::Template.new("www.example.com"), :query => {"x" => ["b", "c"]})).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c"))
end
it "should match when query params are declared as HashIncluding matcher matching params" do
expect(WebMock::RequestPattern.new(:get, Addressable::Template.new("www.example.com"),
:query => WebMock::Matchers::HashIncludingMatcher.new({"a" => ["b", "c"]}))).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c&b=1"))
end
it "should not match when query params are declared as HashIncluding matcher not matching params" do
expect(WebMock::RequestPattern.new(:get, Addressable::Template.new("www.example.com"),
:query => WebMock::Matchers::HashIncludingMatcher.new({"x" => ["b", "c"]}))).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c&b=1"))
end
it "should match when query params are declared as RSpec HashIncluding matcher matching params" do
expect(WebMock::RequestPattern.new(:get, Addressable::Template.new("www.example.com"),
:query => RSpec::Mocks::ArgumentMatchers::HashIncludingMatcher.new({"a" => ["b", "c"]}))).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c&b=1"))
end
it "should not match when query params are declared as RSpec HashIncluding matcher not matching params" do
expect(WebMock::RequestPattern.new(:get, Addressable::Template.new("www.example.com"),
:query => RSpec::Mocks::ArgumentMatchers::HashIncludingMatcher.new({"a" => ["b", "d"]}))).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c&b=1"))
end
end
describe "when uri is described as string" do
it "should match when query params are the same as declared in hash" do
expect(WebMock::RequestPattern.new(:get, "www.example.com", :query => {"a" => ["b", "c"]})).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c"))
end
it "should not match when query params are different than the declared in hash" do
expect(WebMock::RequestPattern.new(:get, "www.example.com", :query => {"a" => ["b", "c"]})).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com?x[]=b&a[]=c"))
end
it "should match when query params are the same as declared as string" do
expect(WebMock::RequestPattern.new(:get, "www.example.com", :query => "a[]=b&a[]=c")).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c"))
end
it "should match when query params are the same as declared both in query option or url" do
expect(WebMock::RequestPattern.new(:get, "www.example.com/?x=3", :query => "a[]=b&a[]=c")).
to match(WebMock::RequestSignature.new(:get, "www.example.com/?x=3&a[]=b&a[]=c"))
end
it "should match when query params are declared as HashIncluding matcher matching params" do
expect(WebMock::RequestPattern.new(:get, "www.example.com",
:query => WebMock::Matchers::HashIncludingMatcher.new({"a" => ["b", "c"]}))).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c&b=1"))
end
it "should not match when query params are declared as HashIncluding matcher not matching params" do
expect(WebMock::RequestPattern.new(:get, "www.example.com",
:query => WebMock::Matchers::HashIncludingMatcher.new({"x" => ["b", "c"]}))).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c&b=1"))
end
it "should match when query params are declared as RSpec HashIncluding matcher matching params" do
expect(WebMock::RequestPattern.new(:get, "www.example.com",
:query => RSpec::Mocks::ArgumentMatchers::HashIncludingMatcher.new({"a" => ["b", "c"]}))).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c&b=1"))
end
it "should not match when query params are declared as RSpec HashIncluding matcher not matching params" do
expect(WebMock::RequestPattern.new(:get, "www.example.com",
:query => RSpec::Mocks::ArgumentMatchers::HashIncludingMatcher.new({"a" => ["b", "d"]}))).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c&b=1"))
end
context "when using query values notation as flat array" do
before :all do
WebMock::Config.instance.query_values_notation = :flat_array
end
it "should not match when repeated query params are not the same as declared as string" do
expect(WebMock::RequestPattern.new(:get, "www.example.com", :query => "a=b&a=c")).
to match(WebMock::RequestSignature.new(:get, "www.example.com?a=b&a=c"))
end
after :all do
WebMock::Config.instance.query_values_notation = nil
end
end
end
end
describe "when matching requests with body" do
it "should match if request body and body pattern are the same" do
expect(WebMock::RequestPattern.new(:get, "www.example.com", :body => "abc")).
to match(WebMock::RequestSignature.new(:get, "www.example.com", :body => "abc"))
end
it "should match if request body matches regexp" do
expect(WebMock::RequestPattern.new(:get, "www.example.com", :body => /^abc$/)).
to match(WebMock::RequestSignature.new(:get, "www.example.com", :body => "abc"))
end
it "should not match if body pattern is different than request body" do
expect(WebMock::RequestPattern.new(:get, "www.example.com", :body => "def")).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com", :body => "abc"))
end
it "should not match if request body doesn't match regexp pattern" do
expect(WebMock::RequestPattern.new(:get, "www.example.com", :body => /^abc$/)).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com", :body => "xabc"))
end
it "should match if pattern doesn't have specified body" do
expect(WebMock::RequestPattern.new(:get, "www.example.com")).
to match(WebMock::RequestSignature.new(:get, "www.example.com", :body => "abc"))
end
it "should not match if pattern has body specified as nil but request body is not empty" do
expect(WebMock::RequestPattern.new(:get, "www.example.com", :body => nil)).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com", :body => "abc"))
end
it "should not match if pattern has empty body but request body is not empty" do
expect(WebMock::RequestPattern.new(:get, "www.example.com", :body => "")).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com", :body => "abc"))
end
it "should not match if pattern has body specified but request has no body" do
expect(WebMock::RequestPattern.new(:get, "www.example.com", :body => "abc")).
not_to match(WebMock::RequestSignature.new(:get, "www.example.com"))
end
describe "when body in pattern is declared as a hash" do
let(:body_hash) { {:a => '1', :b => 'five', 'c' => {'d' => ['e', 'f']}} }
describe "for request with url encoded body" do
it "should match when hash matches body" do
expect(WebMock::RequestPattern.new(:post, 'www.example.com', :body => body_hash)).
to match(WebMock::RequestSignature.new(:post, "www.example.com", :body => 'a=1&c[d][]=e&c[d][]=f&b=five'))
end
it "should match when hash matches body in different order of params" do
expect(WebMock::RequestPattern.new(:post, 'www.example.com', :body => body_hash)).
to match(WebMock::RequestSignature.new(:post, "www.example.com", :body => 'a=1&c[d][]=e&b=five&c[d][]=f'))
end
it "should not match when hash doesn't match url encoded body" do
expect(WebMock::RequestPattern.new(:post, 'www.example.com', :body => body_hash)).
not_to match(WebMock::RequestSignature.new(:post, "www.example.com", :body => 'c[d][]=f&a=1&c[d][]=e'))
end
it "should not match when body is not url encoded" do
expect(WebMock::RequestPattern.new(:post, 'www.example.com', :body => body_hash)).
not_to match(WebMock::RequestSignature.new(:post, "www.example.com", :body => 'foo bar'))
end
it "should match when hash contains regex values" do
expect(WebMock::RequestPattern.new(:post, "www.example.com", :body => {:a => /^\w{5}$/, :b => {:c => /^\d{3}$/}})).
to match(WebMock::RequestSignature.new(:post, "www.example.com", :body => 'a=abcde&b[c]=123'))
end
it "should not match when hash does not contains regex values" do
expect(WebMock::RequestPattern.new(:post, "www.example.com", :body => {:a => /^\d+$/, :b => {:c => /^\d{3}$/}})).
not_to match(WebMock::RequestSignature.new(:post, "www.example.com", :body => 'a=abcde&b[c]=123'))
end
end
describe "for request with json body and content type is set to json" do
it "should match when hash matches body" do
expect(WebMock::RequestPattern.new(:post, 'www.example.com', :body => body_hash)).
to match(WebMock::RequestSignature.new(:post, "www.example.com", :headers => {:content_type => 'application/json'},
:body => "{\"a\":\"1\",\"c\":{\"d\":[\"e\",\"f\"]},\"b\":\"five\"}"))
end
it "should match if hash matches body in different form" do
expect(WebMock::RequestPattern.new(:post, 'www.example.com', :body => body_hash)).
to match(WebMock::RequestSignature.new(:post, "www.example.com", :headers => {:content_type => 'application/json'},
:body => "{\"a\":\"1\",\"b\":\"five\",\"c\":{\"d\":[\"e\",\"f\"]}}"))
end
it "should not match when body is not json" do
expect(WebMock::RequestPattern.new(:post, 'www.example.com', :body => body_hash)).
not_to match(WebMock::RequestSignature.new(:post, "www.example.com",
:headers => {:content_type => 'application/json'}, :body => "foo bar"))
end
it "should not match if request body is different" do
expect(WebMock::RequestPattern.new(:post, 'www.example.com', :body => {:a => 1, :b => 2})).
not_to match(WebMock::RequestSignature.new(:post, "www.example.com",
:headers => {:content_type => 'application/json'}, :body => "{\"a\":1,\"c\":null}"))
end
it "should not match if request body is has less params than pattern" do
expect(WebMock::RequestPattern.new(:post, 'www.example.com', :body => {:a => 1, :b => 2})).
not_to match(WebMock::RequestSignature.new(:post, "www.example.com",
:headers => {:content_type => 'application/json'}, :body => "{\"a\":1}"))
end
it "should not match if request body is has more params than pattern" do
expect(WebMock::RequestPattern.new(:post, 'www.example.com', :body => {:a => 1})).
not_to match(WebMock::RequestSignature.new(:post, "www.example.com",
:headers => {:content_type => 'application/json'}, :body => "{\"a\":1,\"c\":1}"))
end
end
describe "for request with xml body and content type is set to xml" do
let(:body_hash) { {"opt" => {:a => '1', :b => 'five', 'c' => {'d' => ['e', 'f']}}} }
it "should match when hash matches body" do
expect(WebMock::RequestPattern.new(:post, 'www.example.com', :body => body_hash)).
to match(WebMock::RequestSignature.new(:post, "www.example.com", :headers => {:content_type => 'application/xml'},
:body => "
You have reached this web page by typing "example.com", "example.net", or "example.org" into your web browser.
These domain names are reserved for use in documentation and are not available for registration. See RFC 2606, Section 3.
webmock-1.22.6/spec/support/network_connection.rb 0000644 0000041 0000041 00000001267 12646134265 022203 0 ustar www-data www-data module NetworkConnection def self.connect_to(host, port, timeout=nil) addr = Socket.getaddrinfo(host, nil) sock = Socket.new(Socket.const_get(addr[0][0]), Socket::SOCK_STREAM, 0) if timeout secs = Integer(timeout) usecs = Integer((timeout - secs) * 1_000_000) optval = [secs, usecs].pack("l_2") sock.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval sock.setsockopt Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, optval end sock.connect(Socket.pack_sockaddr_in(port, addr[0][3])) sock end def self.is_network_available? begin self.connect_to("173.194.113.176", 80, 5) true rescue false end end end webmock-1.22.6/spec/support/webmock_server.rb 0000644 0000041 0000041 00000002404 12646134265 021302 0 ustar www-data www-data require 'webrick' require 'logger' require 'singleton' class WebMockServer include Singleton attr_reader :port, :started def host_with_port "localhost:#{port}" end def concurrent unless RUBY_PLATFORM =~ /java/ @pid = Process.fork do yield end else Thread.new { yield } end end def start @started = true server = WEBrick::GenericServer.new(:Port => 0, :Logger => Logger.new("/dev/null")) server.logger.level = 0 @port = server.config[:Port] concurrent do ['TERM', 'INT'].each do |signal| trap(signal) do Thread.new do server.shutdown end end end server.start do |socket| socket.puts <<-EOT.gsub(/^\s+\|/, '') |HTTP/1.1 200 OK\r |Date: Fri, 31 Dec 1999 23:59:59 GMT\r |Content-Type: text/html\r |Content-Length: 11\r |Set-Cookie: bar\r |Set-Cookie: foo\r |\r |hello world EOT end end loop do begin TCPSocket.new("localhost", port) sleep 0.1 break rescue Errno::ECONNREFUSED sleep 0.1 end end end def stop if @pid Process.kill('INT', @pid) end end end webmock-1.22.6/spec/acceptance/ 0000755 0000041 0000041 00000000000 12646134265 016312 5 ustar www-data www-data webmock-1.22.6/spec/acceptance/curb/ 0000755 0000041 0000041 00000000000 12646134265 017245 5 ustar www-data www-data webmock-1.22.6/spec/acceptance/curb/curb_spec.rb 0000644 0000041 0000041 00000032263 12646134265 021545 0 ustar www-data www-data require 'spec_helper' require 'acceptance/webmock_shared' unless RUBY_PLATFORM =~ /java/ require 'acceptance/curb/curb_spec_helper' shared_examples_for "Curb" do include CurbSpecHelper include_examples "with WebMock" describe "when doing PUTs" do it "should stub them" do stub_request(:put, "www.example.com").with(:body => "01234") expect(http_request(:put, "http://www.example.com", :body => "01234"). status).to eq("200") end end end describe "Curb features" do before(:each) do WebMock.disable_net_connect! WebMock.reset! end describe "callbacks" do before(:each) do @curl = Curl::Easy.new @curl.url = "http://example.com" end it "should call on_success with 2xx response" do body = "on_success fired" stub_request(:any, "example.com").to_return(:body => body) test = nil @curl.on_success do |c| test = c.body_str end @curl.http_get expect(test).to eq(body) end it "should call on_missing with 4xx response" do response_code = 403 stub_request(:any, "example.com"). to_return(:status => [response_code, "None shall pass"]) test = nil @curl.on_missing do |c, code| test = code end @curl.http_get expect(test).to eq(response_code) end it "should call on_failure with 5xx response" do response_code = 599 stub_request(:any, "example.com"). to_return(:status => [response_code, "Server On Fire"]) test = nil @curl.on_failure do |c, code| test = code end @curl.http_get expect(test).to eq(response_code) end it "should call on_body when response body is read" do body = "on_body fired" stub_request(:any, "example.com"). to_return(:body => body) test = nil @curl.on_body do |data| test = data end @curl.http_get expect(test).to eq(body) end it "should call on_body for each chunk with chunked response" do stub_request(:any, "example.com"). to_return(:body => ["first_chunk", "second_chunk"], :headers => {"Transfer-Encoding" => "chunked"}) test = [] @curl.on_body do |data| test << data end @curl.http_get expect(test).to eq(["first_chunk", "second_chunk"]) end it "should call on_header when response headers are read" do stub_request(:any, "example.com"). to_return(:headers => {:one => 1}) test = [] @curl.on_header do |data| test << data end @curl.http_get expect(test).to eq([ "HTTP/1.1 200 \r\n", 'One: 1' ]) end it "should call on_complete when request is complete" do body = "on_complete fired" stub_request(:any, "example.com").to_return(:body => body) test = nil @curl.on_complete do |curl| test = curl.body_str end @curl.http_get expect(test).to eq(body) end it "should call on_progress when portion of response body is read" do stub_request(:any, "example.com").to_return(:body => "01234") test = nil @curl.on_progress do |*args| expect(args.length).to eq(4) args.each {|arg| expect(arg.is_a?(Float)).to eq(true) } test = true end @curl.http_get expect(test).to eq(true) end it "should call callbacks in correct order on successful request" do stub_request(:any, "example.com") order = [] @curl.on_success {|*args| order << :on_success } @curl.on_missing {|*args| order << :on_missing } @curl.on_failure {|*args| order << :on_failure } @curl.on_header {|*args| order << :on_header } @curl.on_body {|*args| order << :on_body } @curl.on_complete {|*args| order << :on_complete } @curl.on_progress {|*args| order << :on_progress } @curl.http_get expect(order).to eq([:on_progress,:on_header,:on_body,:on_complete,:on_success]) end it "should call callbacks in correct order on failed request" do stub_request(:any, "example.com").to_return(:status => [500, ""]) order = [] @curl.on_success {|*args| order << :on_success } @curl.on_missing {|*args| order << :on_missing } @curl.on_failure {|*args| order << :on_failure } @curl.on_header {|*args| order << :on_header } @curl.on_body {|*args| order << :on_body } @curl.on_complete {|*args| order << :on_complete } @curl.on_progress {|*args| order << :on_progress } @curl.http_get expect(order).to eq([:on_progress,:on_header,:on_body,:on_complete,:on_failure]) end it "should call callbacks in correct order on missing request" do stub_request(:any, "example.com").to_return(:status => [403, ""]) order = [] @curl.on_success {|*args| order << :on_success } @curl.on_missing {|*args| order << :on_missing } @curl.on_failure {|*args| order << :on_failure } @curl.on_header {|*args| order << :on_header } @curl.on_body {|*args| order << :on_body } @curl.on_complete {|*args| order << :on_complete } @curl.on_progress {|*args| order << :on_progress } @curl.http_get expect(order).to eq([:on_progress,:on_header,:on_body,:on_complete,:on_missing]) end end describe '#last_effective_url' do before(:each) do @curl = Curl::Easy.new @curl.url = "http://example.com" end context 'when not following redirects' do before { @curl.follow_location = false } it 'should be the same as #url even with a location header' do stub_request(:any, 'example.com'). to_return(:body => "abc", :status => 302, :headers => { 'Location' => 'http://www.example.com' }) @curl.http_get expect(@curl.last_effective_url).to eq('http://example.com') end end context 'when following redirects' do before { @curl.follow_location = true } it 'should be the same as #url when no location header is present' do stub_request(:any, "example.com") @curl.http_get expect(@curl.last_effective_url).to eq('http://example.com') end it 'should be the value of the location header when present' do stub_request(:any, 'example.com'). to_return(:headers => { 'Location' => 'http://www.example.com' }) stub_request(:any, 'www.example.com') @curl.http_get expect(@curl.last_effective_url).to eq('http://www.example.com') end it 'should work with more than one redirect' do stub_request(:any, 'example.com'). to_return(:headers => { 'Location' => 'http://www.example.com' }) stub_request(:any, 'www.example.com'). to_return(:headers => { 'Location' => 'http://blog.example.com' }) stub_request(:any, 'blog.example.com') @curl.http_get expect(@curl.last_effective_url).to eq('http://blog.example.com') end it 'should maintain the original url' do stub_request(:any, 'example.com'). to_return(:headers => { 'Location' => 'http://www.example.com' }) stub_request(:any, 'www.example.com') @curl.http_get expect(@curl.url).to eq('http://example.com') end it 'should have the redirected-to attrs (body, response code)' do stub_request(:any, 'example.com'). to_return(:body => 'request A', :status => 302, :headers => { 'Location' => 'http://www.example.com' }) stub_request(:any, 'www.example.com').to_return(:body => 'request B') @curl.http_get expect(@curl.body_str).to eq('request B') expect(@curl.response_code).to eq(200) end it 'should follow more than one redirect' do stub_request(:any, 'example.com'). to_return(:headers => { 'Location' => 'http://www.example.com' }) stub_request(:any, 'www.example.com'). to_return(:headers => { 'Location' => 'http://blog.example.com' }) stub_request(:any, 'blog.example.com').to_return(:body => 'blog post') @curl.http_get expect(@curl.url).to eq('http://example.com') expect(@curl.body_str).to eq('blog post') end end end describe "#content_type" do before(:each) do @curl = Curl::Easy.new @curl.url = "http://example.com" end context "when response includes Content-Type header" do it "returns correct content_type" do content_type = "application/json" stub_request(:any, 'example.com'). to_return(:body => "abc", :status => 200, :headers => { 'Content-Type' => content_type }) @curl.http_get expect(@curl.content_type).to eq(content_type) end end context "when response does not include Content-Type header" do it "returns nil for content_type" do stub_request(:any, 'example.com'). to_return(:body => "abc", :status => 200 ) @curl.http_get expect(@curl.content_type).to be_nil end end end describe "#chunked_response?" do before(:each) do @curl = Curl::Easy.new @curl.url = "http://example.com" end it "is true when Transfer-Encoding is 'chunked' and body responds to each" do stub_request(:any, 'example.com'). to_return(:body => ["abc", "def"], :status => 200, :headers => { 'Transfer-Encoding' => 'chunked' }) @curl.http_get expect(@curl).to be_chunked_response end it "is false when Transfer-Encoding is not 'chunked'" do stub_request(:any, 'example.com'). to_return(:body => ["abc", "def"], :status => 200) @curl.http_get expect(@curl).not_to be_chunked_response end it "is false when Transfer-Encoding is 'chunked' but body does not respond to each" do stub_request(:any, 'example.com'). to_return(:body => "abc", :status => 200) @curl.http_get expect(@curl).not_to be_chunked_response end end end describe "Webmock with Curb" do describe "using #http for requests" do it_should_behave_like "Curb" include CurbSpecHelper::DynamicHttp it "should work with uppercase arguments" do stub_request(:get, "www.example.com").to_return(:body => "abc") c = Curl::Easy.new c.url = "http://www.example.com" c.http(:GET) expect(c.body_str).to eq("abc") end it "should alias body to body_str" do stub_request(:get, "www.example.com").to_return(:body => "abc") c = Curl::Easy.new c.url = "http://www.example.com" c.http(:GET) expect(c.body).to eq("abc") end end describe "using #http_* methods for requests" do it_should_behave_like "Curb" include CurbSpecHelper::NamedHttp it "should work with blank arguments for post" do stub_request(:post, "www.example.com").with(:body => "01234") c = Curl::Easy.new c.url = "http://www.example.com" c.post_body = "01234" c.http_post expect(c.response_code).to eq(200) end it "should work with several body arguments for post using the class method" do stub_request(:post, "www.example.com").with(:body => {:user => {:first_name=>'Bartosz', :last_name=>'Blimke'}}) c = Curl::Easy.http_post "http://www.example.com", 'user[first_name]=Bartosz', 'user[last_name]=Blimke' expect(c.response_code).to eq(200) end it "should work with blank arguments for put" do stub_request(:put, "www.example.com").with(:body => "01234") c = Curl::Easy.new c.url = "http://www.example.com" c.put_data = "01234" c.http_put expect(c.response_code).to eq(200) end it "should work with multiple arguments for post" do data = { :name => "john", :address => "111 example ave" } stub_request(:post, "www.example.com").with(:body => data) c = Curl::Easy.new c.url = "http://www.example.com" c.http_post Curl::PostField.content('name', data[:name]), Curl::PostField.content('address', data[:address]) expect(c.response_code).to eq(200) end end describe "using #perform for requests" do it_should_behave_like "Curb" include CurbSpecHelper::Perform end describe "using .http_* methods for requests" do it_should_behave_like "Curb" include CurbSpecHelper::ClassNamedHttp end describe "using .perform for requests" do it_should_behave_like "Curb" include CurbSpecHelper::ClassPerform end end end webmock-1.22.6/spec/acceptance/curb/curb_spec_helper.rb 0000644 0000041 0000041 00000006205 12646134265 023101 0 ustar www-data www-data require 'ostruct' module CurbSpecHelper def http_request(method, uri, options = {}, &block) uri = Addressable::URI.heuristic_parse(uri) body = options[:body] curl = curb_http_request(uri, method, body, options) status, response_headers = WebMock::HttpLibAdapters::CurbAdapter.parse_header_string(curl.header_str) # Deal with the fact that the HTTP spec allows multi-values headers # to either be a single entry with a comma-separated listed of # values, or multiple separate entries response_headers.keys.each do |k| v = response_headers[k] if v.is_a?(Array) response_headers[k] = v.join(', ') end end OpenStruct.new( :body => curl.body_str, :headers => WebMock::Util::Headers.normalize_headers(response_headers), :status => curl.response_code.to_s, :message => status ) end def setup_request(uri, curl, options={}) curl ||= Curl::Easy.new curl.url = uri.omit(:userinfo).to_s curl.username = uri.user curl.password = uri.password curl.timeout = 30 curl.connect_timeout = 30 if headers = options[:headers] headers.each {|k,v| curl.headers[k] = v } end curl end def client_timeout_exception_class Curl::Err::TimeoutError end def connection_refused_exception_class Curl::Err::ConnectionFailedError end def http_library :curb end module DynamicHttp def curb_http_request(uri, method, body, options) curl = setup_request(uri, nil, options) case method when :post curl.post_body = body when :put curl.put_data = body end curl.http(method.to_s.upcase) curl end end module NamedHttp def curb_http_request(uri, method, body, options) curl = setup_request(uri, nil, options) case method when :put, :post curl.send( "http_#{method}", body ) else curl.send( "http_#{method}" ) end curl end end module Perform def curb_http_request(uri, method, body, options) curl = setup_request(uri, nil, options) case method when :post curl.post_body = body when :put curl.put_data = body when :head curl.head = true when :delete curl.delete = true end curl.perform curl end end module ClassNamedHttp def curb_http_request(uri, method, body, options) args = ["http_#{method}", uri] args << body if method == :post || method == :put c = Curl::Easy.send(*args) do |curl| setup_request(uri, curl, options) end c end end module ClassPerform def curb_http_request(uri, method, body, options) args = ["http_#{method}", uri] args << body if method == :post || method == :put c = Curl::Easy.send(*args) do |curl| setup_request(uri, curl, options) case method when :post curl.post_body = body when :put curl.put_data = body when :head curl.head = true when :delete curl.delete = true end end c end end end webmock-1.22.6/spec/acceptance/em_http_request/ 0000755 0000041 0000041 00000000000 12646134265 021522 5 ustar www-data www-data webmock-1.22.6/spec/acceptance/em_http_request/em_http_request_spec.rb 0000644 0000041 0000041 00000033066 12646134265 026301 0 ustar www-data www-data # encoding: utf-8 require 'spec_helper' require 'acceptance/webmock_shared' require 'ostruct' unless RUBY_PLATFORM =~ /java/ require 'acceptance/em_http_request/em_http_request_spec_helper' describe "EM::HttpRequest" do include EMHttpRequestSpecHelper include_context "with WebMock", :no_status_message #functionality only supported for em-http-request 1.x if defined?(EventMachine::HttpConnection) context 'when a real request is made and redirects are followed', :net_connect => true do before { WebMock.allow_net_connect! } # This url redirects to the https URL. let(:http_url) { "http://raw.github.com:80/gist/fb555cb593f3349d53af/6921dd638337d3f6a51b0e02e7f30e3c414f70d6/vcr_gist" } let(:https_url) { http_url.gsub('http', 'https').gsub('80', '443') } def make_request EM.run do request = EM::HttpRequest.new(http_url).get(:redirects => 1) request.callback { EM.stop } end end it "invokes the globally_stub_request hook with both requests" do urls = [] WebMock.globally_stub_request { |r| urls << r.uri.to_s; nil } make_request expect(urls).to eq([http_url, https_url]) end it 'invokes the after_request hook with both requests' do urls = [] WebMock.after_request { |req, res| urls << req.uri.to_s } make_request expect(urls).to eq([http_url, https_url]) end end describe "with middleware" do it "should work with request middleware" do stub_request(:get, "www.example.com").with(:body => 'bar') middleware = Class.new do def request(client, head, body) [{}, 'bar'] end end EM.run do conn = EventMachine::HttpRequest.new('http://www.example.com/') conn.use middleware http = conn.get(:body => 'foo') http.callback do expect(WebMock).to have_requested(:get, "www.example.com").with(:body => 'bar') EM.stop end end end let(:response_middleware) do Class.new do def response(resp) resp.response = 'bar' end end end it "should work with response middleware" do stub_request(:get, "www.example.com").to_return(:body => 'foo') EM.run do conn = EventMachine::HttpRequest.new('http://www.example.com/') conn.use response_middleware http = conn.get http.callback do expect(http.response).to eq('bar') EM.stop end end end let(:webmock_server_url) { "http://#{WebMockServer.instance.host_with_port}/" } shared_examples_for "em-http-request middleware/after_request hook integration" do it 'yields the original raw body to the after_request hook even if a response middleware modifies the body' do yielded_response_body = nil ::WebMock.after_request do |request, response| yielded_response_body = response.body end EM::HttpRequest.use response_middleware EM.run do http = EventMachine::HttpRequest.new(webmock_server_url).get http.callback { EM.stop } end expect(yielded_response_body).to eq("hello world") end end context 'making a real request', :net_connect => true do before { WebMock.allow_net_connect! } include_examples "em-http-request middleware/after_request hook integration" end context 'when the request is stubbed' do before { stub_request(:get, webmock_server_url).to_return(:body => 'hello world') } include_examples "em-http-request middleware/after_request hook integration" end end it 'should trigger error callbacks asynchronously' do stub_request(:get, 'www.example.com').to_timeout called = false EM.run do conn = EventMachine::HttpRequest.new('http://www.example.com/') http = conn.get http.errback do called = true EM.stop end expect(called).to eq(false) end expect(called).to eq(true) end # not pretty, but it works if defined?(EventMachine::Synchrony) describe "with synchrony" do let(:webmock_em_http) { File.expand_path(File.join(File.dirname(__FILE__), "../lib/webmock/http_lib_adapters/em_http_request/em_http_request_1_x.rb")) } before(:each) do # need to reload the webmock em-http adapter after we require synchrony WebMock::HttpLibAdapters::EmHttpRequestAdapter.disable! $".delete webmock_em_http $".delete File.expand_path(File.join(File.dirname(__FILE__), "../../../lib/webmock/http_lib_adapters/em_http_request_adapter.rb")) require 'em-synchrony' require 'em-synchrony/em-http' require File.expand_path(File.join(File.dirname(__FILE__), "../../../lib/webmock/http_lib_adapters/em_http_request_adapter.rb")) end it "should work" do stub_request(:post, /.*.testserver.com*/).to_return(:status => 200, :body => 'ok') expect { EM.run do fiber = Fiber.new do EM::HttpRequest.new("http://www.testserver.com").post :body => "foo=bar&baz=bang", :timeout => 60 EM.stop end fiber.resume end }.not_to raise_error end after(:each) do EM.send(:remove_const, :Synchrony) EM.send(:remove_const, :HTTPMethods) WebMock::HttpLibAdapters::EmHttpRequestAdapter.disable! $".reject! {|path| path.include? "em-http-request"} $".delete webmock_em_http $".delete File.expand_path(File.join(File.dirname(__FILE__), "../../../lib/webmock/http_lib_adapters/em_http_request_adapter.rb")) require 'em-http-request' require File.expand_path(File.join(File.dirname(__FILE__), "../../../lib/webmock/http_lib_adapters/em_http_request_adapter.rb")) end end end end it "should work with streaming" do stub_request(:get, "www.example.com").to_return(:body => "abc") response = "" EM.run { http = EventMachine::HttpRequest.new('http://www.example.com/').get http.stream { |chunk| response = chunk; EM.stop } } expect(response).to eq("abc") end it "should work with responses that use chunked transfer encoding" do stub_request(:get, "www.example.com").to_return(:body => "abc", :headers => { 'Transfer-Encoding' => 'chunked' }) expect(http_request(:get, "http://www.example.com").body).to eq("abc") end it "should work with optional query params" do stub_request(:get, "www.example.com/?x=3&a[]=b&a[]=c").to_return(:body => "abc") expect(http_request(:get, "http://www.example.com/?x=3", :query => {"a" => ["b", "c"]}).body).to eq("abc") end it "should work with optional query params declared as string" do stub_request(:get, "www.example.com/?x=3&a[]=b&a[]=c").to_return(:body => "abc") expect(http_request(:get, "http://www.example.com/?x=3", :query => "a[]=b&a[]=c").body).to eq("abc") end it "should work when the body is passed as a Hash" do stub_request(:post, "www.example.com").with(:body => {:a => "1", :b => "2"}).to_return(:body => "ok") expect(http_request(:post, "http://www.example.com", :body => {:a => "1", :b => "2"}).body).to eq("ok") end if defined?(EventMachine::HttpConnection) it "should work when a file is passed as body" do stub_request(:post, "www.example.com").with(:body => File.read(__FILE__)).to_return(:body => "ok") expect(http_request(:post, "http://www.example.com", :file => __FILE__).body).to eq("ok") end end it "should work with UTF-8 strings" do body = "Привет, Мир!" stub_request(:post, "www.example.com").to_return(:body => body) expect(http_request(:post, "http://www.example.com").body.bytesize).to eq(body.bytesize) end it "should work with multiple requests to the same connection" do stub_request(:get, "www.example.com/foo").to_return(:body => "bar") stub_request(:get, "www.example.com/baz").to_return(:body => "wombat") err1 = nil err2 = nil body1 = nil body2 = nil i = 0 EM.run do conn = EM::HttpRequest.new("http://www.example.com") conn.get(:path => "/foo").callback do |resp| body1 = resp.response i += 1; EM.stop if i == 2 end.errback do |resp| err1 = resp.error i += 1; EM.stop if i == 2 end conn.get(:path => "/baz").callback do |resp| body2 = resp.response i += 1; EM.stop if i == 2 end.errback do |resp| err2 = resp.error i += 1; EM.stop if i == 2 end end expect(err1).to be(nil) expect(err2).to be(nil) expect(body1).to eq("bar") expect(body2).to eq("wombat") end it "should work with multiple requests to the same connection when the first request times out" do stub_request(:get, "www.example.com/foo").to_timeout.then.to_return(:status => 200, :body => "wombat") err = nil body = nil EM.run do conn = EM::HttpRequest.new("http://www.example.com") conn.get(:path => "/foo").callback do |resp| err = :success_from_timeout EM.stop end.errback do |resp| conn.get(:path => "/foo").callback do |resp| expect(resp.response_header.status).to eq(200) body = resp.response EM.stop end.errback do |resp| err = resp.error EM.stop end end end expect(err).to be(nil) expect(body).to eq("wombat") end describe "mocking EM::HttpClient API" do let(:uri) { "http://www.example.com/" } before do stub_request(:get, uri) WebMock::HttpLibAdapters::EmHttpRequestAdapter.enable! end def client(uri, options = {}) client = nil EM.run do client = EventMachine::HttpRequest.new(uri).get(options) client.callback { EM.stop } client.errback { failed } end client end subject { client(uri) } it 'should support #uri' do expect(subject.uri).to eq(Addressable::URI.parse(uri)) end it 'should support #last_effective_url' do expect(subject.last_effective_url).to eq(Addressable::URI.parse(uri)) end context "with a query" do let(:uri) { "http://www.example.com/?a=1&b=2" } subject { client("http://www.example.com/?a=1", :query => { 'b' => 2 }) } it "#request_signature doesn't mutate the original uri" do expect(subject.uri).to eq(Addressable::URI.parse("http://www.example.com/?a=1")) signature = WebMock::RequestRegistry.instance.requested_signatures.hash.keys.first expect(signature.uri).to eq(Addressable::URI.parse(uri)) end end describe 'get_response_cookie' do before(:each) do stub_request(:get, "http://example.org/"). to_return( :status => 200, :body => "", :headers => { 'Set-Cookie' => cookie_string } ) end describe 'success' do context 'with only one cookie' do let(:cookie_name) { 'name_of_the_cookie' } let(:cookie_value) { 'value_of_the_cookie' } let(:cookie_string) { "#{cookie_name}=#{cookie_value}" } it 'successfully gets the cookie' do EM.run { http = EventMachine::HttpRequest.new('http://example.org').get http.errback { fail(http.error) } http.callback { expect(http.get_response_cookie(cookie_name)).to eq(cookie_value) EM.stop } } end end context 'with several cookies' do let(:cookie_name) { 'name_of_the_cookie' } let(:cookie_value) { 'value_of_the_cookie' } let(:cookie_2_name) { 'name_of_the_2nd_cookie' } let(:cookie_2_value) { 'value_of_the_2nd_cookie' } let(:cookie_string) { %W(#{cookie_name}=#{cookie_value} #{cookie_2_name}=#{cookie_2_value}) } it 'successfully gets both cookies' do EM.run { http = EventMachine::HttpRequest.new('http://example.org').get http.errback { fail(http.error) } http.callback { expect(http.get_response_cookie(cookie_name)).to eq(cookie_value) expect(http.get_response_cookie(cookie_2_name)).to eq(cookie_2_value) EM.stop } } end end end describe 'failure' do let(:cookie_string) { 'a=b' } it 'returns nil when no cookie is found' do EM.run { http = EventMachine::HttpRequest.new('http://example.org').get http.errback { fail(http.error) } http.callback { expect(http.get_response_cookie('not_found_cookie')).to eq(nil) EM.stop } } end end end end end end webmock-1.22.6/spec/acceptance/em_http_request/em_http_request_spec_helper.rb 0000644 0000041 0000041 00000003203 12646134265 027626 0 ustar www-data www-data module EMHttpRequestSpecHelper def failed EventMachine.stop fail end def http_request(method, uri, options = {}, &block) @http = nil head = options[:headers] || {} response = nil error = nil error_set = false uri = Addressable::URI.heuristic_parse(uri) EventMachine.run { request = EventMachine::HttpRequest.new("#{uri.normalize.to_s}") http = request.send(method, { :timeout => 30, :body => options[:body], :file => options[:file], :query => options[:query], :head => head.merge('authorization' => [uri.user, uri.password]) }, &block) http.errback { error_set = true error = if http.respond_to?(:errors) http.errors else http.error end failed } http.callback { response = OpenStruct.new({ :body => http.response, :headers => WebMock::Util::Headers.normalize_headers(extract_response_headers(http)), :message => http.response_header.http_reason, :status => http.response_header.status.to_s }) EventMachine.stop } @http = http } raise error.to_s if error_set response end def client_timeout_exception_class "WebMock timeout error" end def connection_refused_exception_class RuntimeError end def http_library :em_http_request end private def extract_response_headers(http) headers = {} if http.response_header http.response_header.each do |k,v| v = v.join(", ") if v.is_a?(Array) headers[k] = v end end headers end end webmock-1.22.6/spec/acceptance/net_http/ 0000755 0000041 0000041 00000000000 12646134265 020137 5 ustar www-data www-data webmock-1.22.6/spec/acceptance/net_http/net_http_shared.rb 0000644 0000041 0000041 00000010550 12646134265 023640 0 ustar www-data www-data shared_examples_for "Net::HTTP" do describe "when making real requests", :net_connect => true do let(:port){ WebMockServer.instance.port } before(:each) do @http = Net::HTTP.new("localhost", port) end it "should return a Net::ReadAdapter from response.body when a real request is made with a block and #read_body", :net_connect => true do response = Net::HTTP.new("localhost", port).request_get('/') { |r| r.read_body { } } expect(response.body).to be_a(Net::ReadAdapter) end it "should handle requests with block passed to read_body", :net_connect => true do body = "" req = Net::HTTP::Get.new("/") Net::HTTP.start("localhost", port) do |http| http.request(req) do |res| res.read_body do |str| body << str end end end expect(body).to match(/hello world/) end it "should connect only once when connected on start", :net_connect => true do @http = Net::HTTP.new('localhost', port) socket_id_before_request = socket_id_after_request = nil @http.start {|conn| socket_id_before_request = conn.instance_variable_get(:@socket).object_id conn.request(Net::HTTP::Get.new("/")) socket_id_after_request = conn.instance_variable_get(:@socket).object_id } if !defined?(WebMock::Config) || WebMock::Config.instance.net_http_connect_on_start expect(socket_id_before_request).not_to eq(nil.object_id) expect(socket_id_after_request).not_to eq(nil.object_id) expect(socket_id_after_request).to eq(socket_id_before_request) else expect(socket_id_before_request).to eq(nil.object_id) expect(socket_id_after_request).not_to eq(nil.object_id) end end describe "without start" do it "should close connection after a real request" do @http.get('/') { } expect(@http).not_to be_started end it "should execute block exactly once" do times = 0 @http.get('/') { times += 1 } expect(times).to eq(1) end it "should have socket open during a real request" do socket_id = nil @http.get('/') { socket_id = @http.instance_variable_get(:@socket).object_id } expect(socket_id).not_to be_nil end it "should be started during a real request" do started = nil @http.get('/') { started = @http.started? } expect(started).to eq(true) expect(@http.started?).to eq(false) end end describe "with start" do it "should close connection after a real request" do @http.start {|conn| conn.get('/') { } } expect(@http).not_to be_started end it "should execute block exactly once" do times = 0 @http.start {|conn| conn.get('/') { times += 1 }} expect(times).to eq(1) end it "should have socket open during a real request" do socket_id = nil @http.start {|conn| conn.get('/') { socket_id = conn.instance_variable_get(:@socket).object_id } } expect(socket_id).not_to be_nil end it "should be started during a real request" do started = nil @http.start {|conn| conn.get('/') { started = conn.started? } } expect(started).to eq(true) expect(@http.started?).to eq(false) end end describe "with start without request block" do it "should close connection after a real request" do @http.start {|conn| conn.get('/') } expect(@http).not_to be_started end it "should have socket open during a real request" do socket_id = nil @http.start {|conn| socket_id = conn.instance_variable_get(:@socket).object_id } expect(socket_id).not_to be_nil end it "should be started during a real request" do started = nil @http.start {|conn| started = conn.started? } expect(started).to eq(true) expect(@http.started?).to eq(false) end end describe "with start without a block and finish" do it "should gracefully start and close connection" do @http.start @http.get("/") expect(@http).to be_started @http.finish expect(@http).not_to be_started end end end end webmock-1.22.6/spec/acceptance/net_http/real_net_http_spec.rb 0000644 0000041 0000041 00000000733 12646134265 024331 0 ustar www-data www-data require 'rubygems' require 'rspec' require 'net/http' require 'net/https' require 'stringio' require 'acceptance/net_http/net_http_shared' require 'support/webmock_server' describe "Real Net:HTTP without webmock", :without_webmock => true do before(:all) do raise "WebMock has no access here!!!" if defined?(WebMock::NetHTTPUtility) WebMockServer.instance.start end after(:all) do WebMockServer.instance.stop end it_should_behave_like "Net::HTTP" end webmock-1.22.6/spec/acceptance/net_http/net_http_spec_helper.rb 0000644 0000041 0000041 00000002716 12646134265 024670 0 ustar www-data www-data module NetHTTPSpecHelper def http_request(method, uri, options = {}, &block) begin uri = URI.parse(uri) rescue uri = Addressable::URI.heuristic_parse(uri) end response = nil clazz = Net::HTTP.const_get("#{method.to_s.capitalize}") req = clazz.new("#{uri.path}#{uri.query ? '?' : ''}#{uri.query}", nil) options[:headers].each do |k,v| if v.is_a?(Array) v.each_with_index do |v,i| i == 0 ? (req[k] = v) : req.add_field(k, v) end else req[k] = v end end if options[:headers] req.basic_auth uri.user, uri.password if uri.user http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == "https" http.use_ssl = true #1.9.1 has a bug with ssl_timeout http.ssl_timeout = 20 unless RUBY_PLATFORM =~ /java/ http.open_timeout = 60 http.read_timeout = 60 end http.verify_mode = OpenSSL::SSL::VERIFY_NONE response = http.start {|http| http.request(req, options[:body], &block) } headers = {} response.each_header {|name, value| headers[name] = value} OpenStruct.new({ :body => response.body, :headers => WebMock::Util::Headers.normalize_headers(headers), :status => response.code, :message => response.message }) end def client_timeout_exception_class Timeout::Error end def connection_refused_exception_class Errno::ECONNREFUSED end def http_library :net_http end end webmock-1.22.6/spec/acceptance/net_http/net_http_spec.rb 0000644 0000041 0000041 00000025224 12646134265 023330 0 ustar www-data www-data require 'spec_helper' require 'ostruct' require 'acceptance/webmock_shared' require 'acceptance/net_http/net_http_spec_helper' require 'acceptance/net_http/net_http_shared' include NetHTTPSpecHelper describe "Net:HTTP" do include_examples "with WebMock" let(:port) { WebMockServer.instance.port } describe "marshalling" do class TestMarshalingInWebMockNetHTTP attr_accessor :r end before(:each) do @b = TestMarshalingInWebMockNetHTTP.new end after(:each) do WebMock.enable! end it "should be possible to load object marshalled when webmock was disabled" do WebMock.disable! original_constants = [ Net::HTTP::Get, Net::HTTP::Post, Net::HTTP::Put, Net::HTTP::Delete, Net::HTTP::Head, Net::HTTP::Options ] @b.r = original_constants original_serialized = Marshal.dump(@b) Marshal.load(original_serialized) WebMock.enable! Marshal.load(original_serialized) end it "should be possible to load object marshalled when webmock was enabled" do WebMock.enable! new_constants = [ Net::HTTP::Get, Net::HTTP::Post, Net::HTTP::Put, Net::HTTP::Delete, Net::HTTP::Head, Net::HTTP::Options ] @b.r = new_constants new_serialized = Marshal.dump(@b) Marshal.load(new_serialized) WebMock.disable! Marshal.load(new_serialized) end end describe "constants" do it "should still have const Get defined on replaced Net::HTTP" do expect(Object.const_get("Net").const_get("HTTP").const_defined?("Get")).to be_truthy end it "should still have const Get within constants on replaced Net::HTTP" do expect(Object.const_get("Net").const_get("HTTP").constants.map(&:to_s)).to include("Get") end it "should still have const Get within constants on replaced Net::HTTP" do expect(Object.const_get("Net").const_get("HTTP").const_get("Get")).not_to be_nil end if Module.method(:const_defined?).arity != 1 it "should still have const Get defined (and not inherited) on replaced Net::HTTP" do expect(Object.const_get("Net").const_get("HTTP").const_defined?("Get", false)).to be_truthy end end if Module.method(:const_get).arity != 1 it "should still be able to get non inherited constant Get on replaced Net::HTTP" do expect(Object.const_get("Net").const_get("HTTP").const_get("Get", false)).not_to be_nil end end if Module.method(:constants).arity != 0 it "should still Get within non inherited constants on replaced Net::HTTP" do expect(Object.const_get("Net").const_get("HTTP").constants(false).map(&:to_s)).to include("Get") end end describe "after WebMock is disabled" do after(:each) do WebMock.enable! end it "Net::HTTP should have the same constants" do orig_consts_number = WebMock::HttpLibAdapters::NetHttpAdapter::OriginalNetHTTP.constants.size Net::HTTP.send(:const_set, "TEST_CONST", 10) expect(Net::HTTP.constants.size).to eq(orig_consts_number + 1) WebMock.disable! expect(Net::HTTP.constants.size).to eq(orig_consts_number + 1) end end end it "should work with block provided" do stub_http_request(:get, "www.example.com").to_return(:body => "abc"*100000) expect(Net::HTTP.start("www.example.com") { |query| query.get("/") }.body).to eq("abc"*100000) end it "raises an ArgumentError if passed headers as symbols" do uri = URI.parse("http://google.com/") http = Net::HTTP.new(uri.host, uri.port) request = Net::HTTP::Get.new(uri.request_uri) # Net::HTTP calls downcase on header keys assigned with []= # In Ruby 1.8.7 symbols do not respond to downcase # # Meaning you can not assign header keys as symbols in ruby 1.8.7 using []= if :symbol.respond_to?(:downcase) request[:InvalidHeaderSinceItsASymbol] = "this will not be valid" else request.instance_eval do @header = request.to_hash.merge({:InvalidHeaderSinceItsASymbol => "this will not be valid"}) end end expect do http.request(request) end.to raise_error ArgumentError, "Net:HTTP does not accept headers as symbols" end it "should handle multiple values for the same response header" do stub_http_request(:get, "www.example.com").to_return(:headers => { 'Set-Cookie' => ['foo=bar', 'bar=bazz'] }) response = Net::HTTP.get_response(URI.parse("http://www.example.com/")) expect(response.get_fields('Set-Cookie')).to eq(['bar=bazz', 'foo=bar']) end it "should yield block on response" do stub_http_request(:get, "www.example.com").to_return(:body => "abc") response_body = "" http_request(:get, "http://www.example.com/") do |response| response_body = response.body end expect(response_body).to eq("abc") end it "should handle Net::HTTP::Post#body" do stub_http_request(:post, "www.example.com").with(:body => "my_params").to_return(:body => "abc") req = Net::HTTP::Post.new("/") req.body = "my_params" expect(Net::HTTP.start("www.example.com") { |http| http.request(req)}.body).to eq("abc") end it "should handle Net::HTTP::Post#body_stream" do stub_http_request(:post, "www.example.com").with(:body => "my_params").to_return(:body => "abc") req = Net::HTTP::Post.new("/") req.body_stream = StringIO.new("my_params") expect(Net::HTTP.start("www.example.com") { |http| http.request(req)}.body).to eq("abc") end it "should behave like Net::HTTP and raise error if both request body and body argument are set" do stub_http_request(:post, "www.example.com").with(:body => "my_params").to_return(:body => "abc") req = Net::HTTP::Post.new("/") req.body = "my_params" expect { Net::HTTP.start("www.example.com") { |http| http.request(req, "my_params")} }.to raise_error("both of body argument and HTTPRequest#body set") end it "should return a Net::ReadAdapter from response.body when a stubbed request is made with a block and #read_body" do WebMock.stub_request(:get, 'http://example.com/').to_return(:body => "the body") response = Net::HTTP.new('example.com', 80).request_get('/') { |r| r.read_body { } } expect(response.body).to be_a(Net::ReadAdapter) end it "should have request 1 time executed in registry after 1 real request", :net_connect => true do WebMock.allow_net_connect! http = Net::HTTP.new('localhost', port) http.get('/') {} expect(WebMock::RequestRegistry.instance.requested_signatures.hash.size).to eq(1) expect(WebMock::RequestRegistry.instance.requested_signatures.hash.values.first).to eq(1) end it "should work with Addressable::URI passed to Net::HTTP.get_response" do stub_request(:get, 'http://www.example.com/hello?a=1').to_return(:body => "abc") expect(Net::HTTP.get_response(Addressable::URI.parse('http://www.example.com/hello?a=1')).body).to eq("abc") end describe "connecting on Net::HTTP.start" do before(:each) do @http = Net::HTTP.new('www.google.com', 443) @http.use_ssl = true @http.verify_mode = OpenSSL::SSL::VERIFY_NONE end describe "when net http is allowed" do it "should not connect to the server until the request", :net_connect => true do WebMock.allow_net_connect! @http.start {|conn| expect(conn.peer_cert).to be_nil } end it "should connect to the server on start", :net_connect => true do WebMock.allow_net_connect!(:net_http_connect_on_start => true) @http.start {|conn| cert = OpenSSL::X509::Certificate.new conn.peer_cert expect(cert).to be_a(OpenSSL::X509::Certificate) } end end describe "when net http is disabled and allowed only for some hosts" do it "should not connect to the server until the request", :net_connect => true do WebMock.disable_net_connect!(:allow => "www.google.com") @http.start {|conn| expect(conn.peer_cert).to be_nil } end it "should connect to the server on start", :net_connect => true do WebMock.disable_net_connect!(:allow => "www.google.com", :net_http_connect_on_start => true) @http.start {|conn| cert = OpenSSL::X509::Certificate.new conn.peer_cert expect(cert).to be_a(OpenSSL::X509::Certificate) } end it "should connect to the server if the URI matches an regex", :net_connect => true do WebMock.disable_net_connect!(:allow => /google.com/) Net::HTTP.get('www.google.com','/') end it "should connect to the server if the URI matches any regex the array", :net_connect => true do WebMock.disable_net_connect!(:allow => [/google.com/, /yahoo.com/]) Net::HTTP.get('www.google.com','/') end end end describe "when net_http_connect_on_start is true" do before(:each) do WebMock.allow_net_connect!(:net_http_connect_on_start => true) end it_should_behave_like "Net::HTTP" end describe "when net_http_connect_on_start is false" do before(:each) do WebMock.allow_net_connect!(:net_http_connect_on_start => false) end it_should_behave_like "Net::HTTP" end describe 'after_request callback support', :net_connect => true do let(:expected_body_regex) { /hello world/ } before(:each) do WebMock.allow_net_connect! @callback_invocation_count = 0 WebMock.after_request do |_, response| @callback_invocation_count += 1 @callback_response = response end end after(:each) do WebMock.reset_callbacks end def perform_get_with_returning_block http_request(:get, "http://localhost:#{port}/") do |response| return response.body end end it "should support the after_request callback on an request with block and read_body" do response_body = '' http_request(:get, "http://localhost:#{port}/") do |response| response.read_body { |fragment| response_body << fragment } end expect(response_body).to match(expected_body_regex) expect(@callback_response.body).to eq(response_body) end it "should support the after_request callback on a request with a returning block" do response_body = perform_get_with_returning_block expect(response_body).to match(expected_body_regex) expect(@callback_response).to be_instance_of(WebMock::Response) expect(@callback_response.body).to eq(response_body) end it "should only invoke the after_request callback once, even for a recursive post request" do Net::HTTP.new('localhost', port).post('/', nil) expect(@callback_invocation_count).to eq(1) end end end webmock-1.22.6/spec/acceptance/http_rb/ 0000755 0000041 0000041 00000000000 12646134265 017754 5 ustar www-data www-data webmock-1.22.6/spec/acceptance/http_rb/http_rb_spec_helper.rb 0000644 0000041 0000041 00000002201 12646134265 024307 0 ustar www-data www-data require "ostruct" module HttpRbSpecHelper def http_request(method, uri, options = {}) response = HTTP.request(method, normalize_uri(uri), options) OpenStruct.new({ :body => response.body.to_s, :headers => normalize_headers(response.headers.to_h), :status => response.code.to_s, :message => response.reason }) end def client_timeout_exception_class return Errno::ETIMEDOUT if HTTP::VERSION < "1.0.0" HTTP::ConnectionError end def connection_refused_exception_class return Errno::ECONNREFUSED if HTTP::VERSION < "1.0.0" HTTP::ConnectionError end def http_library :http_rb end def normalize_uri(uri) Addressable::URI.heuristic_parse(uri).normalize.to_s end def normalize_headers(headers) headers = Hash[headers.map { |k, v| [k, Array(v).join(", ")] }] WebMock::Util::Headers.normalize_headers headers end def stub_simple_request(host, status = 200, headers = {}, body = nil) stub_request(:any, host).to_return({ :status => status, :headers => headers.merge({ "Host" => host }), :body => body }) end end webmock-1.22.6/spec/acceptance/http_rb/http_rb_spec.rb 0000644 0000041 0000041 00000004241 12646134265 022756 0 ustar www-data www-data # encoding: utf-8 require "spec_helper" require "acceptance/webmock_shared" require "acceptance/http_rb/http_rb_spec_helper" describe "HTTP.rb" do include HttpRbSpecHelper include_examples "with WebMock", :no_status_message context "streaming body" do let(:response) { HTTP.get "http://example.com" } before { stub_simple_request "example.com", 302, {}, "abc" } it "works as if it was streamed from socket" do expect(response.body.readpartial 1).to eq "a" end it "fails if body was already streamed" do response.body.to_s expect { response.body.readpartial 1 }.to raise_error end end context "without following redirects" do let(:response) { http_request(:get, "http://example.com") } let(:headers) { response.headers } it "stops on first request" do stub_simple_request("example.com", 302, "Location" => "http://www.example.com") stub_simple_request("www.example.com") expect(headers).to include "Host" => "example.com" end end context "following redirects" do let(:options) { { :follow => true } } let(:response) { http_request(:get, "http://example.com", options) } let(:headers) { response.headers } it "returns response of destination" do stub_simple_request("example.com", 302, "Location" => "http://www.example.com") stub_simple_request("www.example.com") expect(headers).to include "Host" => "www.example.com" end end context "restored request uri on replayed response object" do it "keeps non-default port" do stub_request :get, "example.com:1234/foo" response = HTTP.get "http://example.com:1234/foo" expect(response.uri.to_s).to eq "http://example.com:1234/foo" end it "does not injects default port" do stub_request :get, "example.com/foo" response = HTTP.get "http://example.com/foo" expect(response.uri.to_s).to eq "http://example.com/foo" end it "strips out default port even if it was explicitly given" do stub_request :get, "example.com/foo" response = HTTP.get "http://example.com:80/foo" expect(response.uri.to_s).to eq "http://example.com/foo" end end end webmock-1.22.6/spec/acceptance/webmock_shared.rb 0000644 0000041 0000041 00000002617 12646134265 021622 0 ustar www-data www-data require 'spec_helper' require 'acceptance/shared/enabling_and_disabling_webmock' require 'acceptance/shared/returning_declared_responses' require 'acceptance/shared/callbacks' require 'acceptance/shared/request_expectations' require 'acceptance/shared/stubbing_requests' require 'acceptance/shared/allowing_and_disabling_net_connect' require 'acceptance/shared/precedence_of_stubs' require 'acceptance/shared/complex_cross_concern_behaviors' unless defined? SAMPLE_HEADERS SAMPLE_HEADERS = { "Content-Length" => "8888", "Accept" => "application/json" } ESCAPED_PARAMS = "x=ab%20c&z=%27Stop%21%27%20said%20Fred%20m" NOT_ESCAPED_PARAMS = "z='Stop!' said Fred m&x=ab c" end shared_examples "with WebMock" do |*adapter_info| describe "with WebMock" do let(:webmock_server_url) {"http://#{WebMockServer.instance.host_with_port}/"} before(:each) do WebMock.disable_net_connect! WebMock.reset! end include_context "allowing and disabling net connect", *adapter_info include_context "stubbing requests", *adapter_info include_context "declared responses", *adapter_info include_context "precedence of stubs", *adapter_info include_context "request expectations", *adapter_info include_context "callbacks", *adapter_info include_context "enabled and disabled webmock", *adapter_info include_context "complex cross-concern behaviors", *adapter_info end end webmock-1.22.6/spec/acceptance/shared/ 0000755 0000041 0000041 00000000000 12646134265 017560 5 ustar www-data www-data webmock-1.22.6/spec/acceptance/shared/enabling_and_disabling_webmock.rb 0000644 0000041 0000041 00000004721 12646134265 026235 0 ustar www-data www-data shared_context "enabled and disabled webmock" do |*adapter_info| describe "when webmock is disabled" do before(:each) do WebMock.disable! end after(:each) do WebMock.enable! end include_context "disabled WebMock" end describe "when webmock is enabled again" do before(:each) do WebMock.disable! WebMock.enable! end include_context "enabled WebMock" end describe "when webmock is disabled except this lib" do before(:each) do WebMock.disable!(:except => [http_library]) end after(:each) do WebMock.enable! end include_context "enabled WebMock" end describe "when webmock is enabled except this lib" do before(:each) do WebMock.disable! WebMock.enable!(:except => [http_library]) end after(:each) do WebMock.enable! end include_context "disabled WebMock" end end shared_context "disabled WebMock" do it "should not register executed requests" do http_request(:get, webmock_server_url) expect(a_request(:get, webmock_server_url)).not_to have_been_made end it "should not block unstubbed requests" do expect { http_request(:get, webmock_server_url) }.not_to raise_error end it "should return real response even if there are stubs" do stub_request(:get, /.*/).to_return(:body => "x") expect(http_request(:get, webmock_server_url).body).to eq("hello world") end it "should not invoke any callbacks" do WebMock.reset_callbacks stub_request(:get, webmock_server_url) @called = nil WebMock.after_request { @called = 1 } http_request(:get, webmock_server_url) expect(@called).to eq(nil) end end shared_context "enabled WebMock" do it "should register executed requests" do WebMock.allow_net_connect! http_request(:get, webmock_server_url) expect(a_request(:get, webmock_server_url)).to have_been_made end it "should block unstubbed requests" do expect { http_request(:get, "http://www.example.com/") }.to raise_error(WebMock::NetConnectNotAllowedError) end it "should return stubbed response" do stub_request(:get, /.*/).to_return(:body => "x") expect(http_request(:get, "http://www.example.com/").body).to eq("x") end it "should invoke callbacks" do WebMock.allow_net_connect! WebMock.reset_callbacks @called = nil WebMock.after_request { @called = 1 } http_request(:get, webmock_server_url) expect(@called).to eq(1) end end webmock-1.22.6/spec/acceptance/shared/allowing_and_disabling_net_connect.rb 0000644 0000041 0000041 00000013576 12646134265 027152 0 ustar www-data www-data shared_context "allowing and disabling net connect" do |*adapter_info| describe "when net connect" do describe "is allowed", :net_connect => true do before(:each) do WebMock.allow_net_connect! end it "should make a real web request if request is not stubbed" do expect(http_request(:get, webmock_server_url).status).to eq("200") end it "should make a real https request if request is not stubbed" do unless http_library == :httpclient result = http_request(:get, "https://www.google.com/").body if result.respond_to? :encode result = result.encode( 'UTF-8', 'binary', :invalid => :replace, :undef => :replace, :replace => '' ) end expect(result).to match(/.*google.*/) end end it "should return stubbed response if request was stubbed" do stub_request(:get, "www.example.com").to_return(:body => "abc") expect(http_request(:get, "http://www.example.com/").body).to eq("abc") end end describe "is not allowed" do before(:each) do WebMock.disable_net_connect! end it "should return stubbed response if request was stubbed" do stub_request(:get, "www.example.com").to_return(:body => "abc") expect(http_request(:get, "http://www.example.com/").body).to eq("abc") end it "should return stubbed response if request with path was stubbed" do stub_request(:get, "www.example.com/hello_world").to_return(:body => "abc") expect(http_request(:get, "http://www.example.com/hello_world").body).to eq("abc") end it "should raise exception if request was not stubbed" do expect { http_request(:get, "http://www.example.com/") }.to raise_error(WebMock::NetConnectNotAllowedError, %r(Real HTTP connections are disabled. Unregistered request: GET http://www.example.com/)) end end describe "is not allowed with exception for localhost" do before(:each) do WebMock.disable_net_connect!(:allow_localhost => true) end it "should return stubbed response if request was stubbed" do stub_request(:get, "www.example.com").to_return(:body => "abc") expect(http_request(:get, "http://www.example.com/").body).to eq("abc") end it "should raise exception if request was not stubbed" do expect { http_request(:get, "http://www.example.com/") }.to raise_error(WebMock::NetConnectNotAllowedError, %r(Real HTTP connections are disabled. Unregistered request: GET http://www.example.com/)) end it "should make a real request to localhost" do expect { http_request(:get, "http://localhost:12345/") }.to raise_error(connection_refused_exception_class) end it "should make a real request to 127.0.0.1" do expect { http_request(:get, "http://127.0.0.1:12345/") }.to raise_error(connection_refused_exception_class) end it "should make a real request to 0.0.0.0" do expect { http_request(:get, "http://0.0.0.0:12345/") }.to raise_error(connection_refused_exception_class) end end describe "is not allowed with exception for allowed domains" do let(:host_with_port){ WebMockServer.instance.host_with_port } before(:each) do WebMock.disable_net_connect!(:allow => ["www.example.org", "httpstat.us", host_with_port]) end context "when the host is not allowed" do it "should return stubbed response if request was stubbed" do stub_request(:get, "www.example.com").to_return(:body => "abc") expect(http_request(:get, "http://www.example.com/").body).to eq("abc") end it "should raise exception if request was not stubbed" do expect { http_request(:get, "http://www.example.com/") }.to raise_error(WebMock::NetConnectNotAllowedError, %r(Real HTTP connections are disabled. Unregistered request: GET http://www.example.com/)) end end context "when the host with port is not allowed" do it "should return stubbed response if request was stubbed" do stub_request(:get, "http://localhost:2345").to_return(:body => "abc") expect(http_request(:get, "http://localhost:2345/").body).to eq("abc") end it "should raise exception if request was not stubbed" do expect { http_request(:get, "http://localhost:2345/") }.to raise_error(WebMock::NetConnectNotAllowedError, %r(Real HTTP connections are disabled. Unregistered request: GET http://localhost:2345/)) end end context "when the host is allowed" do it "should raise exception if request was not stubbed" do expect { http_request(:get, "http://www.example.com/") }.to raise_error(WebMock::NetConnectNotAllowedError, %r(Real HTTP connections are disabled. Unregistered request: GET http://www.example.com/)) end it "should make a real request to allowed host", :net_connect => true do expect(http_request(:get, "http://httpstat.us/200").status).to eq("200") end end context "when the host with port is allowed" do it "should make a real request to allowed host", :net_connect => true do expect(http_request(:get, "http://#{host_with_port}/").status).to eq("200") end end context "when the host is allowed but not port" do it "should make a real request to allowed host", :net_connect => true do expect { http_request(:get, "http://localhost:123/") }.to raise_error(WebMock::NetConnectNotAllowedError, %r(Real HTTP connections are disabled. Unregistered request: GET http://localhost:123/)) end end end end end webmock-1.22.6/spec/acceptance/shared/request_expectations.rb 0000644 0000041 0000041 00000121126 12646134265 024366 0 ustar www-data www-data shared_context "request expectations" do |*adapter_info| describe "when request expectations are set" do describe "when net connect is not allowed" do before(:each) do WebMock.disable_net_connect! stub_request(:any, "http://www.example.com") stub_request(:any, "https://www.example.com") end it "should satisfy expectation if request was executed with the same uri and method" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.once }.not_to raise_error end it "should satisfy expectation declared on WebMock.resuest" do expect { http_request(:get, "http://www.example.com/") expect(WebMock.request(:get, "http://www.example.com")).to have_been_made.once }.not_to raise_error end it "should satisfy expectation if request was not expected and not executed" do expect { expect(a_request(:get, "http://www.example.com")).not_to have_been_made }.not_to raise_error end it "should fail if request was not expected but executed" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).not_to have_been_made }.to fail_with(%r(The request GET http://www.example.com/ was not expected to execute but it executed 1 time)) end it "should fail resulting with failure with a message and executed requests listed" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).not_to have_been_made }.to fail_with(%r{The following requests were made:\n\nGET http://www.example.com/.+was made 1 time}) end it "should fail if request was not executed" do expect { expect(a_request(:get, "http://www.example.com")).to have_been_made }.to fail_with(%r(The request GET http://www.example.com/ was expected to execute 1 time but it executed 0 times)) end it "should fail if request was executed to different uri" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.org")).to have_been_made }.to fail_with(%r(The request GET http://www.example.org/ was expected to execute 1 time but it executed 0 times)) end it "should fail if request was executed with different method" do expect { http_request(:post, "http://www.example.com/", :body => "abc") expect(a_request(:get, "http://www.example.com")).to have_been_made }.to fail_with(%r(The request GET http://www.example.com/ was expected to execute 1 time but it executed 0 times)) end it "should satisfy expectation if request was executed with different form of uri" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "www.example.com")).to have_been_made }.not_to raise_error end it "should satisfy expectation if request was executed with different form of uri without port " do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "www.example.com:80")).to have_been_made }.not_to raise_error end it "should satisfy expectation if request was executed with different form of uri with port" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "www.example.com:80")).to have_been_made }.not_to raise_error end it "should fail if request was executed to a different port" do expect { http_request(:get, "http://www.example.com:80/") expect(a_request(:get, "www.example.com:90")).to have_been_made }.to fail_with(%r(The request GET http://www.example.com:90/ was expected to execute 1 time but it executed 0 times)) end it "should satisfy expectation if request was executed with different form of uri with https port" do expect { http_request(:get, "https://www.example.com/") expect(a_request(:get, "https://www.example.com:443/")).to have_been_made }.not_to raise_error end describe "when matching requests with escaped or unescaped uris" do before(:each) do WebMock.disable_net_connect! stub_request(:any, "http://www.example.com/?#{NOT_ESCAPED_PARAMS}") end it "should satisfy expectation if request was executed with escaped params" do expect { http_request(:get, "http://www.example.com/?#{ESCAPED_PARAMS}") expect(a_request(:get, "http://www.example.com/?#{NOT_ESCAPED_PARAMS}")).to have_been_made }.not_to raise_error end it "should satisfy expectation if request was executed with non escaped params" do expect { http_request(:get, "http://www.example.com/?#{NOT_ESCAPED_PARAMS}") expect(a_request(:get, "http://www.example.com/?#{ESCAPED_PARAMS}")).to have_been_made }.not_to raise_error end it "should satisfy expectation if request was executed with escaped params and uri matching regexp was expected" do expect { http_request(:get, "http://www.example.com/?#{ESCAPED_PARAMS}") expect(a_request(:get, /.*example.*/)).to have_been_made }.not_to raise_error end end describe "when matching requests with query params" do before(:each) do stub_request(:any, /.*example.*/) end it "should satisfy expectation if the request was executed with query params declared as a hash in a query option" do expect { http_request(:get, "http://www.example.com/?a[]=b&a[]=c") expect(a_request(:get, "www.example.com").with(:query => {"a" => ["b", "c"]})).to have_been_made }.not_to raise_error end it "should satisfy expectation if the request was executed with query params declared as string in query option" do expect { http_request(:get, "http://www.example.com/?a[]=b&a[]=c") expect(a_request(:get, "www.example.com").with(:query => "a[]=b&a[]=c")).to have_been_made }.not_to raise_error end it "should satisfy expectation if the request was executed with query params both in uri and in query option" do expect { http_request(:get, "http://www.example.com/?x=3&a[]=b&a[]=c") expect(a_request(:get, "www.example.com/?x=3").with(:query => {"a" => ["b", "c"]})).to have_been_made }.not_to raise_error end it "should satisfy expectation if the request was executed with only part query params declared as a hash in a query option" do expect { http_request(:get, "http://www.example.com/?a[]=b&a[]=c&b=1") expect(a_request(:get, "www.example.com").with(:query => hash_including({"a" => ["b", "c"]}))).to have_been_made }.not_to raise_error end end context "when using flat array notation" do before :all do WebMock::Config.instance.query_values_notation = :flat_array end it "should satisfy expectation if request includes different repeated query params in flat array notation" do expect { stub_request(:get, "http://www.example.com/?a=1&a=2") http_request(:get, "http://www.example.com/?a=1&a=2") expect(a_request(:get, "http://www.example.com/?a=1&a=2")).to have_been_made }.not_to raise_error end after :all do WebMock::Config.instance.query_values_notation = nil end end describe "at_most_times" do it "fails if request was made more times than maximum" do expect { http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_most_times(2) }.to fail_with(%r(The request GET http://www.example.com/ was expected to execute at most 2 times but it executed 3 times)) end it "passes if request was made the maximum number of times" do expect { http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_most_times(2) }.not_to raise_error end it "passes if request was made fewer than the maximum number of times" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_most_times(2) }.not_to raise_error end it "passes if request was not made at all" do expect { expect(a_request(:get, "http://www.example.com")).to have_been_made.at_most_times(2) }.not_to raise_error end end describe "at_least_times" do it "fails if request was made fewer times than minimum" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_least_times(2) }.to fail_with(%r(The request GET http://www.example.com/ was expected to execute at least 2 times but it executed 1 time)) end it "passes if request was made the minimum number of times" do expect { http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_least_times(2) }.not_to raise_error end it "passes if request was made more than the minimum number of times" do expect { http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_least_times(2) }.not_to raise_error end context "descriptive at_most_ matcher" do context "at_most_once" do it "succeeds if no request was executed" do expect { expect(a_request(:get, "http://www.example.com")).to have_been_made.at_most_once }.not_to raise_error end it "satisfies expectation if request was executed with the same uri and method once" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_most_once }.not_to raise_error end it "fails if request was executed with the same uri and method twice" do expect { http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_most_once }.to raise_error end end context "at_most_twice" do it "succeeds if no request was executed" do expect { expect(a_request(:get, "http://www.example.com")).to have_been_made.at_most_twice }.not_to raise_error end it "succeeds if too few requests were executed" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_most_twice }.not_to raise_error end it "satisfies expectation if request was executed with the same uri and method twice" do expect { http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_most_twice }.not_to raise_error end it "fails if request was executed with the same uri and method three times" do expect { http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_most_twice }.to raise_error end end end context "descriptive at_least_ matcher" do context "at_least_once" do it "fails if no request was executed" do expect { expect(a_request(:get, "http://www.example.com")).to have_been_made.at_least_once }.to raise_error end it "satisfies expectation if request was executed with the same uri and method once" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_least_once }.not_to raise_error end it "satisfies expectation if request was executed with the same uri and method twice" do expect { http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_least_once }.not_to raise_error end end context "at_least_twice" do it "fails if no request was executed" do expect { expect(a_request(:get, "http://www.example.com")).to have_been_made.at_least_twice }.to raise_error end it "fails if too few requests were executed" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_least_twice }.to raise_error end it "satisfies expectation if request was executed with the same uri and method twice" do expect { http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_least_twice }.not_to raise_error end it "satisfies expectation if request was executed with the same uri and method three times" do expect { http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.at_least_twice }.not_to raise_error end end end end it "should fail if request was made more times than expected" do expect { http_request(:get, "http://www.example.com/") http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made }.to fail_with(%r(The request GET http://www.example.com/ was expected to execute 1 time but it executed 2 times)) end it "should fail if request was made less times than expected" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.twice }.to fail_with(%r(The request GET http://www.example.com/ was expected to execute 2 times but it executed 1 time)) end it "should fail if request was made less times than expected when 3 times expected" do expect { http_request(:get, "http://www.example.com/") expect(a_request(:get, "http://www.example.com")).to have_been_made.times(3) }.to fail_with(%r(The request GET http://www.example.com/ was expected to execute 3 times but it executed 1 time)) end it "should satisfy expectation if request was executed with the same body" do expect { http_request(:post, "http://www.example.com/", :body => "abc") expect(a_request(:post, "www.example.com").with(:body => "abc")).to have_been_made }.not_to raise_error end it "should fail if request was executed with different body" do expect { http_request(:post, "http://www.example.com/", :body => "abc") expect(a_request(:post, "www.example.com"). with(:body => "def")).to have_been_made }.to fail_with(%r(The request POST http://www.example.com/ with body "def" was expected to execute 1 time but it executed 0 times)) end describe "when expected request body is declared as a regexp" do it "should satisfy expectation if request was executed with body matching regexp" do expect { http_request(:post, "http://www.example.com/", :body => "abc") expect(a_request(:post, "www.example.com").with(:body => /^abc$/)).to have_been_made }.not_to raise_error end it "should fail if request was executed with body not matching regexp" do expect { http_request(:post, "http://www.example.com/", :body => "abc") expect(a_request(:post, "www.example.com"). with(:body => /^xabc/)).to have_been_made }.to fail_with(%r(The request POST http://www.example.com/ with body /\^xabc/ was expected to execute 1 time but it executed 0 times)) end end describe "when expected reqest body is declared as a hash" do let(:body_hash) { {:a => '1', :b => 'five', 'c' => {'d' => ['e', 'f']}} } let(:fail_message) {%r(The request POST http://www.example.com/ with body .+ was expected to execute 1 time but it executed 0 times)} describe "when request is made with url encoded body matching hash" do it "should satisfy expectation" do expect { http_request(:post, "http://www.example.com/", :body => 'a=1&c[d][]=e&c[d][]=f&b=five') expect(a_request(:post, "www.example.com").with(:body => body_hash)).to have_been_made }.not_to raise_error end it "should satisfy expectation even if url encoded params have different order" do expect { http_request(:post, "http://www.example.com/", :body => 'a=1&c[d][]=e&b=five&c[d][]=f') expect(a_request(:post, "www.example.com").with(:body => body_hash)).to have_been_made }.not_to raise_error end it "should fail if request is executed with url encoded body not matching hash" do expect { http_request(:post, "http://www.example.com/", :body => 'c[d][]=f&a=1&c[d][]=e') expect(a_request(:post, "www.example.com").with(:body => body_hash)).to have_been_made }.to fail_with(fail_message) end end describe "when request is executed with json body matching hash and Content-Type is set to json" do it "should satisfy expectation" do expect { http_request(:post, "http://www.example.com/", :headers => {'Content-Type' => 'application/json'}, :body => "{\"a\":\"1\",\"c\":{\"d\":[\"e\",\"f\"]},\"b\":\"five\"}") expect(a_request(:post, "www.example.com").with(:body => body_hash)).to have_been_made }.not_to raise_error end it "should satisfy expectation even if json body is in different form" do expect { http_request(:post, "http://www.example.com/", :headers => {'Content-Type' => 'application/json'}, :body => "{\"a\":\"1\",\"b\":\"five\",\"c\":{\"d\":[\"e\",\"f\"]}}") expect(a_request(:post, "www.example.com").with(:body => body_hash)).to have_been_made }.not_to raise_error end it "should satisfy expectation even if json body contains date string" do expect { http_request(:post, "http://www.example.com/", :headers => {'Content-Type' => 'application/json'}, :body => "{\"foo\":\"2010-01-01\"}") expect(a_request(:post, "www.example.com").with(:body => {"foo" => "2010-01-01"})).to have_been_made }.not_to raise_error end end describe "when request is executed with xml body matching hash and content type is set to xml" do let(:body_hash) { { "opt" => {:a => "1", :b => 'five', 'c' => {'d' => ['e', 'f']}} }} it "should satisfy expectation" do expect { http_request(:post, "http://www.example.com/", :headers => {'Content-Type' => 'application/xml'}, :body => ":flat
, :dot
, or
# :subscript
. The :dot
notation is not
# supported for assignment. Default value is :subscript
.
#
# @return [Hash, Array] The query string parsed as a Hash or Array object.
#
# @example
# WebMock::Util::QueryMapper.query_to_values("?one=1&two=2&three=3")
# #=> {"one" => "1", "two" => "2", "three" => "3"}
# WebMock::Util::QueryMapper("?one[two][three]=four").query_values
# #=> {"one" => {"two" => {"three" => "four"}}}
# WebMock::Util::QueryMapper.query_to_values("?one.two.three=four",
# :notation => :dot
# )
# #=> {"one" => {"two" => {"three" => "four"}}}
# WebMock::Util::QueryMapper.query_to_values("?one[two][three]=four",
# :notation => :flat
# )
# #=> {"one[two][three]" => "four"}
# WebMock::Util::QueryMapper.query_to_values("?one.two.three=four",
# :notation => :flat
# )
# #=> {"one.two.three" => "four"}
# WebMock::Util::QueryMapper(
# "?one[two][three][]=four&one[two][three][]=five"
# )
# #=> {"one" => {"two" => {"three" => ["four", "five"]}}}
# WebMock::Util::QueryMapper.query_to_values(
# "?one=two&one=three").query_values(:notation => :flat_array)
# #=> [['one', 'two'], ['one', 'three']]
def query_to_values(query, options={})
return nil if query.nil?
query.force_encoding('utf-8') if query.respond_to?(:force_encoding)
options[:notation] ||= :subscript
if ![:flat, :dot, :subscript, :flat_array].include?(options[:notation])
raise ArgumentError,
'Invalid notation. Must be one of: ' +
'[:flat, :dot, :subscript, :flat_array].'
end
empty_accumulator = :flat_array == options[:notation] ? [] : {}
query_array = collect_query_parts(query)
query_hash = collect_query_hash(query_array, empty_accumulator, options)
normalize_query_hash(query_hash, empty_accumulator, options)
end
def normalize_query_hash(query_hash, empty_accumulator, options)
query_hash.inject(empty_accumulator.dup) do |accumulator, (key, value)|
if options[:notation] == :flat_array
accumulator << [key, value]
else
accumulator[key] = value.kind_of?(Hash) ? dehash(value) : value
end
accumulator
end
end
def collect_query_parts(query)
query_parts = query.split('&').map do |pair|
pair.split('=', 2) if pair && !pair.empty?
end
query_parts.compact
end
def collect_query_hash(query_array, empty_accumulator, options)
query_array.compact.inject(empty_accumulator.dup) do |accumulator, (key, value)|
value = if value.nil?
nil
else
::Addressable::URI.unencode_component(value.gsub(/\+/, ' '))
end
key = Addressable::URI.unencode_component(key)
key = key.dup.force_encoding(Encoding::ASCII_8BIT) if key.respond_to?(:force_encoding)
self.__send__("fill_accumulator_for_#{options[:notation]}", accumulator, key, value)
accumulator
end
end
def fill_accumulator_for_flat(accumulator, key, value)
if accumulator[key]
raise ArgumentError, "Key was repeated: #{key.inspect}"
end
accumulator[key] = value
end
def fill_accumulator_for_flat_array(accumulator, key, value)
accumulator << [key, value]
end
def fill_accumulator_for_dot(accumulator, key, value)
array_value = false
subkeys = key.split(".")
current_hash = accumulator
subkeys[0..-2].each do |subkey|
current_hash[subkey] = {} unless current_hash[subkey]
current_hash = current_hash[subkey]
end
if array_value
if current_hash[subkeys.last] && !current_hash[subkeys.last].is_a?(Array)
current_hash[subkeys.last] = [current_hash[subkeys.last]]
end
current_hash[subkeys.last] = [] unless current_hash[subkeys.last]
current_hash[subkeys.last] << value
else
current_hash[subkeys.last] = value
end
end
def fill_accumulator_for_subscript(accumulator, key, value)
current_node = accumulator
subkeys = key.split(/(?=\[\w)/)
subkeys[0..-2].each do |subkey|
node = subkey =~ /\[\]\z/ ? [] : {}
subkey = subkey.gsub(/[\[\]]/, '')
if current_node.is_a? Array
container = current_node.find { |n| n.is_a?(Hash) && n.has_key?(subkey) }
if container
current_node = container[subkey]
else
current_node << {subkey => node}
current_node = node
end
else
current_node[subkey] = node unless current_node[subkey]
current_node = current_node[subkey]
end
end
last_key = subkeys.last
array_value = !!(last_key =~ /\[\]$/)
last_key = last_key.gsub(/[\[\]]/, '')
if current_node.is_a? Array
container = current_node.find { |n| n.is_a?(Hash) && n.has_key?(last_key) }
if container
if array_value
container[last_key] << value
else
container[last_key] = value
end
else
if array_value
current_node << {last_key => [value]}
else
current_node << {last_key => value}
end
end
else
if array_value
current_node[last_key] = [] unless current_node[last_key]
current_node[last_key] << value
else
current_node[last_key] = value
end
end
end
##
# Sets the query component for this URI from a Hash object.
# This method produces a query string using the :subscript notation.
# An empty Hash will result in a nil query.
#
# @param [Hash, #to_hash, Array] new_query_values The new query values.
def values_to_query(new_query_values, options = {})
options[:notation] ||= :subscript
return if new_query_values.nil?
unless new_query_values.is_a?(Array)
unless new_query_values.respond_to?(:to_hash)
raise TypeError,
"Can't convert #{new_query_values.class} into Hash."
end
new_query_values = new_query_values.to_hash
new_query_values = new_query_values.inject([]) do |object, (key, value)|
key = key.to_s if key.is_a?(::Symbol) || key.nil?
if value.is_a?(Array)
value.each { |v| object << [key.to_s + '[]', v] }
elsif value.is_a?(Hash)
value.each { |k, v| object << ["#{key.to_s}[#{k}]", v]}
else
object << [key.to_s, value]
end
object
end
# Useful default for OAuth and caching.
# Only to be used for non-Array inputs. Arrays should preserve order.
begin
new_query_values.sort! # may raise for non-comparable values
rescue NoMethodError, ArgumentError
# ignore
end
end
buffer = ''
new_query_values.each do |parent, value|
encoded_parent = ::Addressable::URI.encode_component(
parent.dup, ::Addressable::URI::CharacterClasses::UNRESERVED
)
buffer << "#{to_query(encoded_parent, value, options)}&"
end
buffer.chop
end
def dehash(hash)
hash.each do |(key, value)|
if value.is_a?(::Hash)
hash[key] = self.dehash(value)
end
end
if hash != {} && hash.keys.all? { |key| key =~ /^\d+$/ }
hash.sort.inject([]) do |accu, (_, value)|
accu << value; accu
end
else
hash
end
end
##
# Joins and converts parent and value into a properly encoded and
# ordered URL query.
#
# @private
# @param [String] parent an URI encoded component.
# @param [Array, Hash, Symbol, #to_str] value
#
# @return [String] a properly escaped and ordered URL query.
# new_query_values have form [['key1', 'value1'], ['key2', 'value2']]
def to_query(parent, value, options = {})
options[:notation] ||= :subscript
case value
when ::Hash
value = value.map do |key, val|
[
::Addressable::URI.encode_component(key.to_s.dup, ::Addressable::URI::CharacterClasses::UNRESERVED),
val
]
end
value.sort!
buffer = ''
value.each do |key, val|
new_parent = options[:notation] != :flat_array ? "#{parent}[#{key}]" : parent
buffer << "#{to_query(new_parent, val, options)}&"
end
buffer.chop
when ::Array
buffer = ''
value.each_with_index do |val, i|
new_parent = options[:notation] != :flat_array ? "#{parent}[#{i}]" : parent
buffer << "#{to_query(new_parent, val, options)}&"
end
buffer.chop
when NilClass
parent
else
encoded_value = Addressable::URI.encode_component(
value.to_s.dup, Addressable::URI::CharacterClasses::UNRESERVED
)
"#{parent}=#{encoded_value}"
end
end
end
end
end
webmock-1.22.6/lib/webmock/util/json.rb 0000644 0000041 0000041 00000006261 12646134265 017747 0 ustar www-data www-data # This is a copy of https://github.com/jnunemaker/crack/blob/master/lib/crack/json.rb
# with date parsing removed
# Copyright (c) 2004-2008 David Heinemeier Hansson
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module WebMock
module Util
class JSON
class ParseError < StandardError; end
def self.parse(json)
yaml = unescape(convert_json_to_yaml(json))
YAML.load(yaml)
rescue ArgumentError => e
raise ParseError, "Invalid JSON string: #{yaml}, Error: #{e.inspect}"
end
protected
def self.unescape(str)
str.gsub(/\\u([0-9a-f]{4})/) { [$1.hex].pack("U") }
end
# Ensure that ":" and "," are always followed by a space
def self.convert_json_to_yaml(json) #:nodoc:
scanner, quoting, marks, pos, times = StringScanner.new(json), false, [], nil, []
while scanner.scan_until(/(\\['"]|['":,\\]|\\.)/)
case char = scanner[1]
when '"', "'"
if !quoting
quoting = char
pos = scanner.pos
elsif quoting == char
quoting = false
end
when ":",","
marks << scanner.pos - 1 unless quoting
when "\\"
scanner.skip(/\\/)
end
end
if marks.empty?
json.gsub(/\\\//, '/')
else
left_pos = [-1].push(*marks)
right_pos = marks << json.bytesize
output = []
if RUBY_VERSION != "1.9.2"
left_pos.each_with_index do |left, i|
if json.respond_to?(:byteslice)
output << json.byteslice(left.succ..right_pos[i])
else
output << json[left.succ..right_pos[i]]
end
end
else
json_as_binary = json.force_encoding("binary")
left_pos.each_with_index do |left, i|
output << json_as_binary[left.succ..right_pos[i]]
end
output.map! do |binary_str|
binary_str.force_encoding("UTF-8")
end
end
output = output * " "
times.each { |i| output[i-1] = ' ' }
output.gsub!(/\\\//, '/')
output
end
end
end
end
end
webmock-1.22.6/lib/webmock/util/uri.rb 0000644 0000041 0000041 00000007414 12646134265 017576 0 ustar www-data www-data module WebMock
module Util
class URI
module CharacterClasses
USERINFO = Addressable::URI::CharacterClasses::UNRESERVED + Addressable::URI::CharacterClasses::SUB_DELIMS + "\\:"
end
ADDRESSABLE_URIS = Hash.new do |hash, key|
hash[key] = Addressable::URI.heuristic_parse(key)
end
NORMALIZED_URIS = Hash.new do |hash, uri|
normalized_uri = WebMock::Util::URI.heuristic_parse(uri)
if normalized_uri.query_values
sorted_query_values = sort_query_values(WebMock::Util::QueryMapper.query_to_values(normalized_uri.query, :notation => Config.instance.query_values_notation) || {})
normalized_uri.query = WebMock::Util::QueryMapper.values_to_query(sorted_query_values, :notation => WebMock::Config.instance.query_values_notation)
end
normalized_uri = normalized_uri.normalize #normalize! is slower
normalized_uri.query = normalized_uri.query.gsub("+", "%2B") if normalized_uri.query
normalized_uri.port = normalized_uri.inferred_port unless normalized_uri.port
hash[uri] = normalized_uri
end
def self.heuristic_parse(uri)
ADDRESSABLE_URIS[uri].dup
end
def self.normalize_uri(uri)
return uri if uri.is_a?(Regexp)
uri = 'http://' + uri unless uri.match('^https?://') if uri.is_a?(String)
NORMALIZED_URIS[uri].dup
end
def self.variations_of_uri_as_strings(uri_object)
normalized_uri = normalize_uri(uri_object.dup).freeze
uris = [ normalized_uri ]
if normalized_uri.path == '/'
uris = uris_with_trailing_slash_and_without(uris)
end
uris = uris_encoded_and_unencoded(uris)
if normalized_uri.port == Addressable::URI.port_mapping[normalized_uri.scheme]
uris = uris_with_inferred_port_and_without(uris)
end
if normalized_uri.scheme == "http"
uris = uris_with_scheme_and_without(uris)
end
uris.map {|uri| uri.to_s.gsub(/^\/\//,'') }.uniq
end
def self.strip_default_port_from_uri_string(uri_string)
case uri_string
when %r{^http://} then uri_string.sub(%r{:80(/|$)}, '\1')
when %r{^https://} then uri_string.sub(%r{:443(/|$)}, '\1')
else uri_string
end
end
def self.encode_unsafe_chars_in_userinfo(userinfo)
Addressable::URI.encode_component(userinfo, WebMock::Util::URI::CharacterClasses::USERINFO)
end
def self.is_uri_localhost?(uri)
uri.is_a?(Addressable::URI) &&
%w(localhost 127.0.0.1 0.0.0.0).include?(uri.host)
end
private
def self.sort_query_values(query_values)
sorted_query_values = query_values.sort
query_values.is_a?(Hash) ? Hash[*sorted_query_values.inject([]) { |values, pair| values + pair}] : sorted_query_values
end
def self.uris_with_inferred_port_and_without(uris)
uris.map { |uri|
uri = uri.dup.force_encoding(Encoding::ASCII_8BIT) if uri.respond_to?(:force_encoding)
[ uri, uri.gsub(%r{(:80)|(:443)}, "").freeze ]
}.flatten
end
def self.uris_encoded_and_unencoded(uris)
uris.map do |uri|
[ uri.to_s, Addressable::URI.unencode(uri, String).freeze ]
end.flatten
end
def self.uris_with_scheme_and_without(uris)
uris.map { |uri|
uri = uri.dup.force_encoding(Encoding::ASCII_8BIT) if uri.respond_to?(:force_encoding)
[ uri, uri.gsub(%r{^https?://},"").freeze ]
}.flatten
end
def self.uris_with_trailing_slash_and_without(uris)
uris = uris.map { |uri|
uri = uri.dup.force_encoding(Encoding::ASCII_8BIT) if uri.respond_to?(:force_encoding)
[ uri, uri.omit(:path).freeze ]
}.flatten
end
end
end
end
webmock-1.22.6/lib/webmock/util/hash_keys_stringifier.rb 0000644 0000041 0000041 00000001104 12646134265 023350 0 ustar www-data www-data module WebMock
module Util
class HashKeysStringifier
def self.stringify_keys!(arg, options = {})
case arg
when Array
arg.map { |elem|
options[:deep] ? stringify_keys!(elem, options) : elem
}
when Hash
Hash[
*arg.map { |key, value|
k = key.is_a?(Symbol) ? key.to_s : key
v = (options[:deep] ? stringify_keys!(value, options) : value)
[k,v]
}.inject([]) {|r,x| r + x}]
else
arg
end
end
end
end
end
webmock-1.22.6/lib/webmock/util/hash_validator.rb 0000644 0000041 0000041 00000000766 12646134265 021772 0 ustar www-data www-data module WebMock
class HashValidator
def initialize(hash)
@hash = hash
end
#This code is based on https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/hash/keys.rb
def validate_keys(*valid_keys)
valid_keys.flatten!
@hash.each_key do |k|
unless valid_keys.include?(k)
raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}")
end
end
end
end
end
webmock-1.22.6/lib/webmock/util/version_checker.rb 0000644 0000041 0000041 00000006351 12646134265 022147 0 ustar www-data www-data # This code was created based on https://github.com/myronmarston/vcr/blob/master/lib/vcr/util/version_checker.rb
# Thanks to @myronmarston
# Copyright (c) 2010-2012 Myron Marston
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
module WebMock
class VersionChecker
def initialize(library_name, library_version, min_patch_level, max_minor_version = nil)
@library_name, @library_version = library_name, library_version
@min_patch_level, @max_minor_version = min_patch_level, max_minor_version
@major, @minor, @patch = parse_version(library_version)
@min_major, @min_minor, @min_patch = parse_version(min_patch_level)
@max_major, @max_minor = parse_version(max_minor_version) if max_minor_version
@comparison_result = compare_version
end
def check_version!
warn_about_too_low if too_low?
warn_about_too_high if too_high?
end
private
def too_low?
@comparison_result == :too_low
end
def too_high?
@comparison_result == :too_high
end
def warn_about_too_low
warn_in_red "You are using #{@library_name} #{@library_version}. " +
"WebMock supports version #{version_requirement}."
end
def warn_about_too_high
warn_in_red "You are using #{@library_name} #{@library_version}. " +
"WebMock is known to work with #{@library_name} #{version_requirement}. " +
"It may not work with this version."
end
def warn_in_red(text)
Kernel.warn colorize(text, "\e[31m")
end
def compare_version
case
when @major < @min_major then :too_low
when @max_major && @major > @max_major then :too_high
when @major > @min_major then :ok
when @minor < @min_minor then :too_low
when @max_minor && @minor > @max_minor then :too_high
when @minor > @min_minor then :ok
when @patch < @min_patch then :too_low
end
end
def version_requirement
req = ">= #{@min_patch_level}"
req += ", < #{@max_major}.#{@max_minor + 1}" if @max_minor
req
end
def parse_version(version)
version.split('.').map { |v| v.to_i }
end
def colorize(text, color_code)
"#{color_code}#{text}\e[0m"
end
end
end
webmock-1.22.6/lib/webmock/util/hash_counter.rb 0000644 0000041 0000041 00000001176 12646134265 021460 0 ustar www-data www-data require 'thread'
module WebMock
module Util
class Util::HashCounter
attr_accessor :hash
def initialize
self.hash = {}
@order = {}
@max = 0
@lock = ::Mutex.new
end
def put key, num=1
@lock.synchronize do
hash[key] = (hash[key] || 0) + num
@order[key] = @max = @max + 1
end
end
def get key
@lock.synchronize do
hash[key] || 0
end
end
def each(&block)
@order.to_a.sort {|a, b| a[1] <=> b[1]}.each do |a|
block.call(a[0], hash[a[0]])
end
end
end
end
end
webmock-1.22.6/lib/webmock/rspec/ 0000755 0000041 0000041 00000000000 12646134265 016603 5 ustar www-data www-data webmock-1.22.6/lib/webmock/rspec/matchers.rb 0000644 0000041 0000041 00000001131 12646134265 020732 0 ustar www-data www-data require 'webmock'
require 'webmock/rspec/matchers/request_pattern_matcher'
require 'webmock/rspec/matchers/webmock_matcher'
module WebMock
module Matchers
def have_been_made
WebMock::RequestPatternMatcher.new
end
def have_been_requested
WebMock::RequestPatternMatcher.new
end
def have_not_been_made
WebMock::RequestPatternMatcher.new.times(0)
end
def have_requested(method, uri)
WebMock::WebMockMatcher.new(method, uri)
end
def have_not_requested(method, uri)
WebMock::WebMockMatcher.new(method, uri).times(0)
end
end
end
webmock-1.22.6/lib/webmock/rspec/matchers/ 0000755 0000041 0000041 00000000000 12646134265 020411 5 ustar www-data www-data webmock-1.22.6/lib/webmock/rspec/matchers/request_pattern_matcher.rb 0000644 0000041 0000041 00000003406 12646134265 025671 0 ustar www-data www-data module WebMock
class RequestPatternMatcher
def initialize
@request_execution_verifier = RequestExecutionVerifier.new
end
def once
@request_execution_verifier.expected_times_executed = 1
self
end
def twice
@request_execution_verifier.expected_times_executed = 2
self
end
def times(times)
@request_execution_verifier.expected_times_executed = times.to_i
self
end
def at_least_once
@request_execution_verifier.at_least_times_executed = 1
self
end
def at_least_twice
@request_execution_verifier.at_least_times_executed = 2
self
end
def at_least_times(times)
@request_execution_verifier.at_least_times_executed = times.to_i
self
end
def at_most_once
@request_execution_verifier.at_most_times_executed = 1
self
end
def at_most_twice
@request_execution_verifier.at_most_times_executed = 2
self
end
def at_most_times(times)
@request_execution_verifier.at_most_times_executed = times.to_i
self
end
def matches?(request_pattern)
@request_execution_verifier.request_pattern = request_pattern
@request_execution_verifier.matches?
end
def does_not_match?(request_pattern)
@request_execution_verifier.request_pattern = request_pattern
@request_execution_verifier.does_not_match?
end
def failure_message
@request_execution_verifier.failure_message
end
def failure_message_when_negated
@request_execution_verifier.failure_message_when_negated
end
def description
@request_execution_verifier.description
end
# RSpec 2 compatibility:
alias_method :negative_failure_message, :failure_message_when_negated
end
end
webmock-1.22.6/lib/webmock/rspec/matchers/webmock_matcher.rb 0000644 0000041 0000041 00000002271 12646134265 024072 0 ustar www-data www-data module WebMock
class WebMockMatcher
def initialize(method, uri)
@request_execution_verifier = RequestExecutionVerifier.new
@request_execution_verifier.request_pattern = RequestPattern.new(method, uri)
end
def once
@request_execution_verifier.expected_times_executed = 1
self
end
def twice
@request_execution_verifier.expected_times_executed = 2
self
end
def with(options = {}, &block)
@request_execution_verifier.request_pattern.with(options, &block)
self
end
def times(times)
@request_execution_verifier.expected_times_executed = times.to_i
self
end
def matches?(webmock)
@request_execution_verifier.matches?
end
def does_not_match?(webmock)
@request_execution_verifier.does_not_match?
end
def failure_message
@request_execution_verifier.failure_message
end
def failure_message_when_negated
@request_execution_verifier.failure_message_when_negated
end
def description
@request_execution_verifier.description
end
# RSpec 2 compatibility:
alias_method :negative_failure_message, :failure_message_when_negated
end
end
webmock-1.22.6/lib/webmock/rspec.rb 0000644 0000041 0000041 00000001413 12646134265 017127 0 ustar www-data www-data require 'webmock'
# RSpec 1.x and 2.x compatibility
if defined?(RSpec::Expectations::ExpectationNotMetError)
RSPEC_NAMESPACE = RSPEC_CONFIGURER = RSpec
elsif defined?(Spec) && defined?(Spec.configure)
RSPEC_NAMESPACE = Spec
RSPEC_CONFIGURER = Spec::Runner
else
begin
require 'rspec/core'
require 'rspec/expectations'
RSPEC_NAMESPACE = RSPEC_CONFIGURER = RSpec
rescue LoadError
require 'spec'
RSPEC_NAMESPACE = Spec
RSPEC_CONFIGURER = Spec::Runner
end
end
require 'webmock/rspec/matchers'
RSPEC_CONFIGURER.configure { |config|
config.include WebMock::API
config.include WebMock::Matchers
config.after(:each) do
WebMock.reset!
end
}
WebMock::AssertionFailure.error_class = RSPEC_NAMESPACE::Expectations::ExpectationNotMetError
webmock-1.22.6/lib/webmock/request_stub.rb 0000644 0000041 0000041 00000005220 12646134265 020540 0 ustar www-data www-data module WebMock
class RequestStub
attr_accessor :request_pattern
def initialize(method, uri)
@request_pattern = RequestPattern.new(method, uri)
@responses_sequences = []
self
end
def with(params = {}, &block)
@request_pattern.with(params, &block)
self
end
def to_return(*response_hashes, &block)
if block
@responses_sequences << ResponsesSequence.new([ResponseFactory.response_for(block)])
else
@responses_sequences << ResponsesSequence.new([*response_hashes].flatten.map {|r| ResponseFactory.response_for(r)})
end
self
end
alias_method :and_return, :to_return
def to_rack(app, options={})
@responses_sequences << ResponsesSequence.new([RackResponse.new(app)])
end
def to_raise(*exceptions)
@responses_sequences << ResponsesSequence.new([*exceptions].flatten.map {|e|
ResponseFactory.response_for(:exception => e)
})
self
end
alias_method :and_raise, :to_raise
def to_timeout
@responses_sequences << ResponsesSequence.new([ResponseFactory.response_for(:should_timeout => true)])
self
end
alias_method :and_timeout, :to_timeout
def response
if @responses_sequences.empty?
WebMock::Response.new
elsif @responses_sequences.length > 1
@responses_sequences.shift if @responses_sequences.first.end?
@responses_sequences.first.next_response
else
@responses_sequences[0].next_response
end
end
def has_responses?
!@responses_sequences.empty?
end
def then
self
end
def times(number)
raise "times(N) accepts integers >= 1 only" if !number.is_a?(Fixnum) || number < 1
if @responses_sequences.empty?
raise "Invalid WebMock stub declaration." +
" times(N) can be declared only after response declaration."
end
@responses_sequences.last.times_to_repeat += number-1
self
end
def matches?(request_signature)
self.request_pattern.matches?(request_signature)
end
def to_s
self.request_pattern.to_s
end
def self.from_request_signature(signature)
stub = self.new(signature.method.to_sym, signature.uri.to_s)
if signature.body.to_s != ''
body = if signature.url_encoded?
WebMock::Util::QueryMapper.query_to_values(signature.body, :notation => Config.instance.query_values_notation)
else
signature.body
end
stub.with(:body => body)
end
if (signature.headers && !signature.headers.empty?)
stub.with(:headers => signature.headers)
end
stub
end
end
end
webmock-1.22.6/lib/webmock/request_signature.rb 0000644 0000041 0000041 00000002453 12646134265 021571 0 ustar www-data www-data module WebMock
class RequestSignature
attr_accessor :method, :uri, :body
attr_reader :headers
def initialize(method, uri, options = {})
self.method = method.to_sym
self.uri = uri.is_a?(Addressable::URI) ? uri : WebMock::Util::URI.normalize_uri(uri)
assign_options(options)
end
def to_s
string = "#{self.method.to_s.upcase}"
string << " #{WebMock::Util::URI.strip_default_port_from_uri_string(self.uri.to_s)}"
string << " with body '#{body.to_s}'" if body && body.to_s != ''
if headers && !headers.empty?
string << " with headers #{WebMock::Util::Headers.sorted_headers_string(headers)}"
end
string
end
def headers=(headers)
@headers = WebMock::Util::Headers.normalize_headers(headers)
end
def hash
self.to_s.hash
end
def eql?(other)
self.to_s == other.to_s
end
alias == eql?
def url_encoded?
!!(headers && headers['Content-Type'] == 'application/x-www-form-urlencoded')
end
def json_headers?
!!(headers && headers['Content-Type'] == 'application/json')
end
private
def assign_options(options)
self.body = options[:body] if options.has_key?(:body)
self.headers = options[:headers] if options.has_key?(:headers)
end
end
end
webmock-1.22.6/lib/webmock.rb 0000644 0000041 0000041 00000003704 12646134265 016020 0 ustar www-data www-data require 'singleton'
require 'addressable/uri'
require 'addressable/template'
require 'crack/xml'
require 'webmock/deprecation'
require 'webmock/version'
require 'webmock/errors'
require 'webmock/util/query_mapper'
require 'webmock/util/uri'
require 'webmock/util/headers'
require 'webmock/util/hash_counter'
require 'webmock/util/hash_keys_stringifier'
require 'webmock/util/json'
require 'webmock/util/version_checker'
require 'webmock/util/hash_validator'
require 'webmock/matchers/hash_including_matcher'
require 'webmock/request_pattern'
require 'webmock/request_signature'
require 'webmock/responses_sequence'
require 'webmock/request_stub'
require 'webmock/response'
require 'webmock/rack_response'
require 'webmock/stub_request_snippet'
require 'webmock/request_signature_snippet'
require 'webmock/request_body_diff'
require 'webmock/assertion_failure'
require 'webmock/request_execution_verifier'
require 'webmock/config'
require 'webmock/callback_registry'
require 'webmock/request_registry'
require 'webmock/stub_registry'
require 'webmock/api'
require 'webmock/http_lib_adapters/http_lib_adapter_registry'
require 'webmock/http_lib_adapters/http_lib_adapter'
require 'webmock/http_lib_adapters/net_http'
require 'webmock/http_lib_adapters/http_rb_adapter'
require 'webmock/http_lib_adapters/httpclient_adapter'
require 'webmock/http_lib_adapters/patron_adapter'
require 'webmock/http_lib_adapters/curb_adapter'
require 'webmock/http_lib_adapters/em_http_request_adapter'
require 'webmock/http_lib_adapters/typhoeus_hydra_adapter'
require 'webmock/http_lib_adapters/excon_adapter'
require 'webmock/http_lib_adapters/manticore_adapter'
require 'webmock/webmock'
if RUBY_VERSION <= "1.8.7" && Addressable::VERSION::STRING >= "2.4.0"
raise StandardError,
<<-ERR
\n\e[31m
Addressable dropped support for Ruby 1.8.7 on version 2.4.0,
please add the following to your Gemfile to be able to use WebMock:
gem 'addressable', '< 2.4.0'\e[0m\n
ERR
end
webmock-1.22.6/gemfiles/ 0000755 0000041 0000041 00000000000 12646134265 015065 5 ustar www-data www-data webmock-1.22.6/gemfiles/ruby_1_8.gemfile 0000644 0000041 0000041 00000000425 12646134265 020050 0 ustar www-data www-data # This file was generated by Appraisal
source "http://rubygems.org/"
gem "addressable", ">= 2.3.6", "< 2.4.0"
group :development do
gem "rake"
end
group :test do
gem "minitest_tu_shim", "1.3.2"
end
platforms :jruby do
gem "jruby-openssl"
end
gemspec :path => "../"
webmock-1.22.6/metadata.yml 0000644 0000041 0000041 00000030317 12646134265 015601 0 ustar www-data www-data --- !ruby/object:Gem::Specification
name: webmock
version: !ruby/object:Gem::Version
version: 1.22.6
platform: ruby
authors:
- Bartosz Blimke
autorequire:
bindir: bin
cert_chain: []
date: 2016-01-10 00:00:00 Z
dependencies:
- !ruby/object:Gem::Dependency
name: addressable
prerelease: false
requirement: &id001 !ruby/object:Gem::Requirement
requirements:
- - ">="
- !ruby/object:Gem::Version
version: 2.3.6
type: :runtime
version_requirements: *id001
- !ruby/object:Gem::Dependency
name: crack
prerelease: false
requirement: &id002 !ruby/object:Gem::Requirement
requirements:
- - ">="
- !ruby/object:Gem::Version
version: 0.3.2
type: :runtime
version_requirements: *id002
- !ruby/object:Gem::Dependency
name: hashdiff
prerelease: false
requirement: &id003 !ruby/object:Gem::Requirement
requirements:
- &id014
- ">="
- !ruby/object:Gem::Version
version: "0"
type: :runtime
version_requirements: *id003
- !ruby/object:Gem::Dependency
name: rspec
prerelease: false
requirement: &id004 !ruby/object:Gem::Requirement
requirements:
- - ">="
- !ruby/object:Gem::Version
version: 3.1.0
type: :development
version_requirements: *id004
- !ruby/object:Gem::Dependency
name: httpclient
prerelease: false
requirement: &id005 !ruby/object:Gem::Requirement
requirements:
- - ">="
- !ruby/object:Gem::Version
version: 2.2.4
type: :development
version_requirements: *id005
- !ruby/object:Gem::Dependency
name: patron
prerelease: false
requirement: &id006 !ruby/object:Gem::Requirement
requirements:
- - "="
- !ruby/object:Gem::Version
version: 0.4.18
type: :development
version_requirements: *id006
- !ruby/object:Gem::Dependency
name: em-http-request
prerelease: false
requirement: &id007 !ruby/object:Gem::Requirement
requirements:
- - ">="
- !ruby/object:Gem::Version
version: 1.0.2
type: :development
version_requirements: *id007
- !ruby/object:Gem::Dependency
name: http
prerelease: false
requirement: &id008 !ruby/object:Gem::Requirement
requirements:
- - "="
- !ruby/object:Gem::Version
version: 0.7.3
type: :development
version_requirements: *id008
- !ruby/object:Gem::Dependency
name: curb
prerelease: false
requirement: &id009 !ruby/object:Gem::Requirement
requirements:
- - <=
- !ruby/object:Gem::Version
version: 0.8.6
type: :development
version_requirements: *id009
- !ruby/object:Gem::Dependency
name: typhoeus
prerelease: false
requirement: &id010 !ruby/object:Gem::Requirement
requirements:
- - ">="
- !ruby/object:Gem::Version
version: 0.5.0
type: :development
version_requirements: *id010
- !ruby/object:Gem::Dependency
name: excon
prerelease: false
requirement: &id011 !ruby/object:Gem::Requirement
requirements:
- - ">="
- !ruby/object:Gem::Version
version: 0.27.5
type: :development
version_requirements: *id011
- !ruby/object:Gem::Dependency
name: minitest
prerelease: false
requirement: &id012 !ruby/object:Gem::Requirement
requirements:
- - ~>
- !ruby/object:Gem::Version
version: 5.0.0
type: :development
version_requirements: *id012
- !ruby/object:Gem::Dependency
name: rdoc
prerelease: false
requirement: &id013 !ruby/object:Gem::Requirement
requirements:
- - ">"
- !ruby/object:Gem::Version
version: 3.5.0
type: :development
version_requirements: *id013
- !ruby/object:Gem::Dependency
name: rack
prerelease: false
requirement: &id015 !ruby/object:Gem::Requirement
requirements:
- *id014
type: :development
version_requirements: *id015
- !ruby/object:Gem::Dependency
name: appraisal
prerelease: false
requirement: &id016 !ruby/object:Gem::Requirement
requirements:
- - ~>
- !ruby/object:Gem::Version
version: "2.0"
type: :development
version_requirements: *id016
description: WebMock allows stubbing HTTP requests and setting expectations on HTTP requests.
email:
- bartosz.blimke@gmail.com
executables: []
extensions: []
extra_rdoc_files: []
files:
- .gemtest
- .gitignore
- .rspec-tm
- .travis.yml
- Appraisals
- CHANGELOG.md
- Gemfile
- LICENSE
- README.md
- Rakefile
- gemfiles/ruby_1_8.gemfile
- lib/webmock.rb
- lib/webmock/api.rb
- lib/webmock/assertion_failure.rb
- lib/webmock/callback_registry.rb
- lib/webmock/config.rb
- lib/webmock/cucumber.rb
- lib/webmock/deprecation.rb
- lib/webmock/errors.rb
- lib/webmock/http_lib_adapters/curb_adapter.rb
- lib/webmock/http_lib_adapters/em_http_request/em_http_request_0_x.rb
- lib/webmock/http_lib_adapters/em_http_request/em_http_request_1_x.rb
- lib/webmock/http_lib_adapters/em_http_request_adapter.rb
- lib/webmock/http_lib_adapters/excon_adapter.rb
- lib/webmock/http_lib_adapters/http_lib_adapter.rb
- lib/webmock/http_lib_adapters/http_lib_adapter_registry.rb
- lib/webmock/http_lib_adapters/http_rb/client.rb
- lib/webmock/http_lib_adapters/http_rb/request.rb
- lib/webmock/http_lib_adapters/http_rb/response.rb
- lib/webmock/http_lib_adapters/http_rb/streamer.rb
- lib/webmock/http_lib_adapters/http_rb/webmock.rb
- lib/webmock/http_lib_adapters/http_rb_adapter.rb
- lib/webmock/http_lib_adapters/httpclient_adapter.rb
- lib/webmock/http_lib_adapters/manticore_adapter.rb
- lib/webmock/http_lib_adapters/net_http.rb
- lib/webmock/http_lib_adapters/net_http_response.rb
- lib/webmock/http_lib_adapters/patron_adapter.rb
- lib/webmock/http_lib_adapters/typhoeus_hydra_adapter.rb
- lib/webmock/matchers/hash_including_matcher.rb
- lib/webmock/minitest.rb
- lib/webmock/rack_response.rb
- lib/webmock/request_body_diff.rb
- lib/webmock/request_execution_verifier.rb
- lib/webmock/request_pattern.rb
- lib/webmock/request_registry.rb
- lib/webmock/request_signature.rb
- lib/webmock/request_signature_snippet.rb
- lib/webmock/request_stub.rb
- lib/webmock/response.rb
- lib/webmock/responses_sequence.rb
- lib/webmock/rspec.rb
- lib/webmock/rspec/matchers.rb
- lib/webmock/rspec/matchers/request_pattern_matcher.rb
- lib/webmock/rspec/matchers/webmock_matcher.rb
- lib/webmock/stub_registry.rb
- lib/webmock/stub_request_snippet.rb
- lib/webmock/test_unit.rb
- lib/webmock/util/hash_counter.rb
- lib/webmock/util/hash_keys_stringifier.rb
- lib/webmock/util/hash_validator.rb
- lib/webmock/util/headers.rb
- lib/webmock/util/json.rb
- lib/webmock/util/query_mapper.rb
- lib/webmock/util/uri.rb
- lib/webmock/util/version_checker.rb
- lib/webmock/version.rb
- lib/webmock/webmock.rb
- minitest/test_helper.rb
- minitest/test_webmock.rb
- minitest/webmock_spec.rb
- spec/acceptance/curb/curb_spec.rb
- spec/acceptance/curb/curb_spec_helper.rb
- spec/acceptance/em_http_request/em_http_request_spec.rb
- spec/acceptance/em_http_request/em_http_request_spec_helper.rb
- spec/acceptance/excon/excon_spec.rb
- spec/acceptance/excon/excon_spec_helper.rb
- spec/acceptance/http_rb/http_rb_spec.rb
- spec/acceptance/http_rb/http_rb_spec_helper.rb
- spec/acceptance/httpclient/httpclient_spec.rb
- spec/acceptance/httpclient/httpclient_spec_helper.rb
- spec/acceptance/manticore/manticore_spec.rb
- spec/acceptance/manticore/manticore_spec_helper.rb
- spec/acceptance/net_http/net_http_shared.rb
- spec/acceptance/net_http/net_http_spec.rb
- spec/acceptance/net_http/net_http_spec_helper.rb
- spec/acceptance/net_http/real_net_http_spec.rb
- spec/acceptance/patron/patron_spec.rb
- spec/acceptance/patron/patron_spec_helper.rb
- spec/acceptance/shared/allowing_and_disabling_net_connect.rb
- spec/acceptance/shared/callbacks.rb
- spec/acceptance/shared/complex_cross_concern_behaviors.rb
- spec/acceptance/shared/enabling_and_disabling_webmock.rb
- spec/acceptance/shared/precedence_of_stubs.rb
- spec/acceptance/shared/request_expectations.rb
- spec/acceptance/shared/returning_declared_responses.rb
- spec/acceptance/shared/stubbing_requests.rb
- spec/acceptance/typhoeus/typhoeus_hydra_spec.rb
- spec/acceptance/typhoeus/typhoeus_hydra_spec_helper.rb
- spec/acceptance/webmock_shared.rb
- spec/quality_spec.rb
- spec/spec_helper.rb
- spec/support/example_curl_output.txt
- spec/support/my_rack_app.rb
- spec/support/network_connection.rb
- spec/support/webmock_server.rb
- spec/unit/api_spec.rb
- spec/unit/errors_spec.rb
- spec/unit/http_lib_adapters/http_lib_adapter_registry_spec.rb
- spec/unit/http_lib_adapters/http_lib_adapter_spec.rb
- spec/unit/matchers/hash_including_matcher_spec.rb
- spec/unit/rack_response_spec.rb
- spec/unit/request_body_diff_spec.rb
- spec/unit/request_execution_verifier_spec.rb
- spec/unit/request_pattern_spec.rb
- spec/unit/request_registry_spec.rb
- spec/unit/request_signature_snippet_spec.rb
- spec/unit/request_signature_spec.rb
- spec/unit/request_stub_spec.rb
- spec/unit/response_spec.rb
- spec/unit/stub_registry_spec.rb
- spec/unit/stub_request_snippet_spec.rb
- spec/unit/util/hash_counter_spec.rb
- spec/unit/util/hash_keys_stringifier_spec.rb
- spec/unit/util/headers_spec.rb
- spec/unit/util/json_spec.rb
- spec/unit/util/query_mapper_spec.rb
- spec/unit/util/uri_spec.rb
- spec/unit/util/version_checker_spec.rb
- spec/unit/webmock_spec.rb
- test/http_request.rb
- test/shared_test.rb
- test/test_helper.rb
- test/test_webmock.rb
- webmock.gemspec
homepage: http://github.com/bblimke/webmock
licenses:
- MIT
metadata: {}
post_install_message:
rdoc_options: []
require_paths:
- lib
required_ruby_version: !ruby/object:Gem::Requirement
requirements:
- *id014
required_rubygems_version: !ruby/object:Gem::Requirement
requirements:
- *id014
requirements: []
rubyforge_project: webmock
rubygems_version: 2.0.17
signing_key:
specification_version: 4
summary: Library for stubbing HTTP requests in Ruby.
test_files:
- spec/acceptance/curb/curb_spec.rb
- spec/acceptance/curb/curb_spec_helper.rb
- spec/acceptance/em_http_request/em_http_request_spec.rb
- spec/acceptance/em_http_request/em_http_request_spec_helper.rb
- spec/acceptance/excon/excon_spec.rb
- spec/acceptance/excon/excon_spec_helper.rb
- spec/acceptance/http_rb/http_rb_spec.rb
- spec/acceptance/http_rb/http_rb_spec_helper.rb
- spec/acceptance/httpclient/httpclient_spec.rb
- spec/acceptance/httpclient/httpclient_spec_helper.rb
- spec/acceptance/manticore/manticore_spec.rb
- spec/acceptance/manticore/manticore_spec_helper.rb
- spec/acceptance/net_http/net_http_shared.rb
- spec/acceptance/net_http/net_http_spec.rb
- spec/acceptance/net_http/net_http_spec_helper.rb
- spec/acceptance/net_http/real_net_http_spec.rb
- spec/acceptance/patron/patron_spec.rb
- spec/acceptance/patron/patron_spec_helper.rb
- spec/acceptance/shared/allowing_and_disabling_net_connect.rb
- spec/acceptance/shared/callbacks.rb
- spec/acceptance/shared/complex_cross_concern_behaviors.rb
- spec/acceptance/shared/enabling_and_disabling_webmock.rb
- spec/acceptance/shared/precedence_of_stubs.rb
- spec/acceptance/shared/request_expectations.rb
- spec/acceptance/shared/returning_declared_responses.rb
- spec/acceptance/shared/stubbing_requests.rb
- spec/acceptance/typhoeus/typhoeus_hydra_spec.rb
- spec/acceptance/typhoeus/typhoeus_hydra_spec_helper.rb
- spec/acceptance/webmock_shared.rb
- spec/quality_spec.rb
- spec/spec_helper.rb
- spec/support/example_curl_output.txt
- spec/support/my_rack_app.rb
- spec/support/network_connection.rb
- spec/support/webmock_server.rb
- spec/unit/api_spec.rb
- spec/unit/errors_spec.rb
- spec/unit/http_lib_adapters/http_lib_adapter_registry_spec.rb
- spec/unit/http_lib_adapters/http_lib_adapter_spec.rb
- spec/unit/matchers/hash_including_matcher_spec.rb
- spec/unit/rack_response_spec.rb
- spec/unit/request_body_diff_spec.rb
- spec/unit/request_execution_verifier_spec.rb
- spec/unit/request_pattern_spec.rb
- spec/unit/request_registry_spec.rb
- spec/unit/request_signature_snippet_spec.rb
- spec/unit/request_signature_spec.rb
- spec/unit/request_stub_spec.rb
- spec/unit/response_spec.rb
- spec/unit/stub_registry_spec.rb
- spec/unit/stub_request_snippet_spec.rb
- spec/unit/util/hash_counter_spec.rb
- spec/unit/util/hash_keys_stringifier_spec.rb
- spec/unit/util/headers_spec.rb
- spec/unit/util/json_spec.rb
- spec/unit/util/query_mapper_spec.rb
- spec/unit/util/uri_spec.rb
- spec/unit/util/version_checker_spec.rb
- spec/unit/webmock_spec.rb
- test/http_request.rb
- test/shared_test.rb
- test/test_helper.rb
- test/test_webmock.rb
webmock-1.22.6/test/ 0000755 0000041 0000041 00000000000 12646134265 014251 5 ustar www-data www-data webmock-1.22.6/test/http_request.rb 0000644 0000041 0000041 00000001323 12646134265 017324 0 ustar www-data www-data require 'ostruct'
module HttpRequestTestHelper
def http_request(method, uri, options = {})
begin
uri = URI.parse(uri)
rescue
uri = Addressable::URI.heuristic_parse(uri)
end
response = nil
clazz = ::Net::HTTP.const_get("#{method.to_s.capitalize}")
req = clazz.new("#{uri.path}#{uri.query ? '?' : ''}#{uri.query}", options[:headers])
req.basic_auth uri.user, uri.password if uri.user
http = ::Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == "https"
response = http.start {|http|
http.request(req, options[:body])
}
OpenStruct.new({
:body => response.body,
:headers => response,
:status => response.code })
end
end webmock-1.22.6/test/test_webmock.rb 0000644 0000041 0000041 00000000307 12646134265 017264 0 ustar www-data www-data require File.expand_path(File.dirname(__FILE__) + '/test_helper')
require File.expand_path(File.dirname(__FILE__) + '/shared_test')
class TestWebMock < Test::Unit::TestCase
include SharedTest
end
webmock-1.22.6/test/test_helper.rb 0000644 0000041 0000041 00000001157 12646134265 017120 0 ustar www-data www-data require 'rubygems'
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'webmock/test_unit'
require 'test/unit'
class Test::Unit::TestCase
AssertionFailedError = Test::Unit::AssertionFailedError rescue MiniTest::Assertion
def assert_raise_with_message(e, message, &block)
e = assert_raises(e, &block)
if message.is_a?(Regexp)
assert_match(message, e.message)
else
assert_equal(message, e.message)
end
end
def assert_fail(message, &block)
assert_raise_with_message(AssertionFailedError, message, &block)
end
end
webmock-1.22.6/test/shared_test.rb 0000644 0000041 0000041 00000007460 12646134265 017112 0 ustar www-data www-data require File.expand_path(File.dirname(__FILE__) + '/http_request')
module SharedTest
include HttpRequestTestHelper
def setup
super
@stub_http = stub_http_request(:any, "http://www.example.com")
@stub_https = stub_http_request(:any, "https://www.example.com")
end
def test_assert_requested_with_stub_and_block_raises_error
assert_raises ArgumentError do
assert_requested(@stub_http) {}
end
end
def test_assert_not_requested_with_stub_and_block_raises_error
assert_raises ArgumentError do
assert_not_requested(@stub_http) {}
end
end
def test_error_on_non_stubbed_request
default_ruby_headers = (RUBY_VERSION >= "1.9.1") ? "{'Accept'=>'*/*', 'User-Agent'=>'Ruby'}" : "{'Accept'=>'*/*'}"
assert_raise_with_message(WebMock::NetConnectNotAllowedError, %r{Real HTTP connections are disabled. Unregistered request: GET http://www.example.net/ with headers}) do
http_request(:get, "http://www.example.net/")
end
end
def test_verification_that_expected_request_occured
http_request(:get, "http://www.example.com/")
assert_requested(:get, "http://www.example.com", :times => 1)
assert_requested(:get, "http://www.example.com")
end
def test_verification_that_expected_stub_occured
http_request(:get, "http://www.example.com/")
assert_requested(@stub_http, :times => 1)
assert_requested(@stub_http)
end
def test_verification_that_expected_request_didnt_occur
expected_message = "The request GET http://www.example.com/ was expected to execute 1 time but it executed 0 times"
expected_message << "\n\nThe following requests were made:\n\nNo requests were made.\n============================================================"
assert_fail(expected_message) do
assert_requested(:get, "http://www.example.com")
end
end
def test_verification_that_expected_request_didnt_occur
expected_message = "The request ANY http://www.example.com/ was expected to execute 1 time but it executed 0 times"
expected_message << "\n\nThe following requests were made:\n\nNo requests were made.\n============================================================"
assert_fail(expected_message) do
assert_requested(@stub_http)
end
end
def test_verification_that_expected_request_occured_with_body_and_headers
http_request(:get, "http://www.example.com/",
:body => "abc", :headers => {'A' => 'a'})
assert_requested(:get, "http://www.example.com",
:body => "abc", :headers => {'A' => 'a'})
end
def test_verification_that_expected_request_occured_with_query_params
stub_request(:any, "http://www.example.com").with(:query => hash_including({"a" => ["b", "c"]}))
http_request(:get, "http://www.example.com/?a[]=b&a[]=c&x=1")
assert_requested(:get, "http://www.example.com",
:query => hash_including({"a" => ["b", "c"]}))
end
def test_verification_that_non_expected_request_didnt_occur
expected_message = %r(The request GET http://www.example.com/ was not expected to execute but it executed 1 time\n\nThe following requests were made:\n\nGET http://www.example.com/ with headers .+ was made 1 time\n\n============================================================)
assert_fail(expected_message) do
http_request(:get, "http://www.example.com/")
assert_not_requested(:get, "http://www.example.com")
end
end
def test_verification_that_non_expected_stub_didnt_occur
expected_message = %r(The request ANY http://www.example.com/ was not expected to execute but it executed 1 time\n\nThe following requests were made:\n\nGET http://www.example.com/ with headers .+ was made 1 time\n\n============================================================)
assert_fail(expected_message) do
http_request(:get, "http://www.example.com/")
assert_not_requested(@stub_http)
end
end
end
webmock-1.22.6/.gitignore 0000644 0000041 0000041 00000000434 12646134265 015263 0 ustar www-data www-data ## MAC OS
.DS_Store
## TEXTMATE
*.tmproj
tmtags
## EMACS
*~
\#*
.\#*
## VIM
.*.sw[a-z]
## RubyMine and related
.idea
## PROJECT::GENERAL
coverage
rdoc
pkg
## PROJECT::SPECIFIC
*.gem
.bundle
Gemfile.lock
gemfiles/*.gemfile.lock
pkg/*
tmp/*
*.rbc
*.rbx
.ruby-gemset
.ruby-version
webmock-1.22.6/.rspec-tm 0000644 0000041 0000041 00000000037 12646134265 015025 0 ustar www-data www-data --rspec-version 2.0.0
--bundler webmock-1.22.6/LICENSE 0000644 0000041 0000041 00000002047 12646134265 014302 0 ustar www-data www-data Copyright (c) 2009-2010 Bartosz Blimke
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
webmock-1.22.6/Appraisals 0000644 0000041 0000041 00000000106 12646134265 015311 0 ustar www-data www-data appraise "ruby_1_8" do
gem "addressable", ">= 2.3.6", "< 2.4.0"
end
webmock-1.22.6/CHANGELOG.md 0000644 0000041 0000041 00000132501 12646134265 015105 0 ustar www-data www-data # Changelog
## 1.22.6
* Fixes [issue](https://github.com/bblimke/webmock/issues/568) around
WebMock restricting [Addressable](https://github.com/sporkmonger/addressable)
version, based on Ruby 1.8.7 for all versions of Ruby.
This change inverts that, and forces Ruby 1.8.7 users to specify in thier
Gemfile an Addressable version < 2.4.0.
Thanks to [PikachuEXE](https://github.com/PikachuEXE) and
[Matthew Rudy Jacobs](https://github.com/matthewrudy).
## 1.22.5
* Fixes [bug](https://github.com/bblimke/webmock/issues/565) where WebMock tries
to alias a method that is deprecated in Ruby Versions > 1.9.2 ('sysread' for class 'StringIO')
Thanks to [Marcos Acosta](https://github.com/mmaa) for discovering this bug.
## 1.22.4
* Adds support for JSONClient (a subclass of HTTPClient)
Thanks to [Andrew Kozin](https://github.com/nepalez)
* Adds support for Ruby 2.3.0
Thanks to [Charles Pence](https://github.com/cpence)
* Adds support for [http](https://github.com/httprb/http) versions >= 1.0.0
Thanks to [Alexey Zapparov](https://github.com/ixti)
* Fixes support for Ruby 1.8.7 by restrciting Addressable version < 2.4.0
Thanks to [Matthew Rudy Jacobs](https://github.com/matthewrudy)
## 1.22.3
* Return "effective_url" attribute in Typhoeus::Response
Thanks to [Senya](https://github.com/cmrd-senya)
## 1.22.2
* Fix: prevents adding an extra =true to urls with parameters without values
Thanks to [David Begin](https://github.com/davidbegin)
## 1.22.1
* Adds Rack as a development dependency and removes require rack/utils in main lib.
Thanks to [Keenan Brock](https://github.com/kbrock)
## 1.22.0
All the credit for preparing this release go to [David Begin](https://github.com/davidbegin)!
* Adds [Manticore](https://github.com/cheald/manticore) support.
Thanks to [Mike Knepper](https://github.com/mikeknep), [David Abdemoulaie](https://github.com/hobodave)
* Update to Show a hash diff for requests that have stubs with a body.
Thanks to [yurivm](https://github.com/yurivm)
* Update to mirror Net::HTTP handling of headers as symbols
* Update to ignore non-comparable-values error when sorting
query values, because sorting is just a convience.
Thanks to [Magne Land](https://github.com/magneland)
* Covert Boolean values to Strings when using them to define
the body of a request.
Thanks to [Krzysztof Rygielski](https://github.com/riggy)
* Fixes WebMock's parsing Multibyte characters
Thanks to [Zhao Wen](https://github.com/VincentZhao)
* Updates to be compatible with httpclient 2.6.0
* Converts keys from symbols to strings when for QueryMapper.to_query
Thanks to [Ramon Tayag](https://github.com/ramontayag)
* Restricts http.rb version to 0.7.3 for Ruby 1.8.7
* Fixes issue emulating em-http-request's handling of multiple requests.
Thanks to [Matt Palmer](https://github.com/mpalmer)
* WebMock requires only the necessary parts of crack to avoid pulling in safe_yaml
Thanks to [Johannes Schlumberger](https://github.com/spjsschl)
## 1.21.0
* Support for http.rb >= 0.8.0
Thanks to [Zachary Anker](https://github.com/zanker), [Aleksey V. Zapparov](https://github.com/ixti)
* Support for http.rb 0.7.0
Thanks to [Mattias Putman](https://github.com/challengee)
* Added support for RSpec3-like `and_return`, `and_raise`, `and_timeout` syntax.
Thanks to [Franky Wahl](https://github.com/frankywahl)
* Restricted Curb support up to version 0.8.6. WebMock specs fail with Curb 0.8.7.
## 1.20.4
* Fixed support for `hash_including` matcher in RSpec 3
## 1.20.3
* `with` method raises error if provided without options hash and without block
* `with` and `to_return` raise an error if invoked with invalid keys in options hash.
## 1.20.2
* WebMock provides a helpful error message if an incompatible object is given as response body.
Thanks to [Mark Lorenz](https://github.com/dapplebeforedawn)
## 1.20.1
* `assert_requested` and `assert_not_requested` accept `at_least_times` and `at_most_times` options
Thanks to [Dan Buettner](https://github.com/Capncavedan)
* Silenced `instance variable undefined` warnings in Curb adapted.
Thanks to [Sven Riedel](https://github.com/sriedel)
## 1.20.0
* Add support for on_missing callback of Curb::Easy
Thanks to [Tasos Stathopoulos](https://github.com/astathopoulos)
* Add at_least_times and at_most_times matchers
Thanks to [Dan Buettner](https://github.com/Capncavedan)
## 1.19.0
* Fixed issue with Excon adapter giving warning message when redirects middleware was enabled.
Thanks to [Theo Hultberg](https://github.com/iconara) for reporting that.
* Fixed issue with `undefined method 'valid_request_keys' for Excon::Utils:Module`
Thanks to [Pablo Jairala](https://github.com/davidjairala)
* Fixed query mapper to encode `'one' => ['1','2']` as `'one[]=1&one[]=2'`.
Thanks to [Insoo Buzz Jung](https://github.com/insoul)
* Improved cookies support for em-http-request
Thanks to [Carlos Alonso Pérez](https://github.com/calonso)
* Fix HTTP Gem adapter to ensure uri attribute is set on response object.
Thanks to [Aleksey V. Zapparov](https://github.com/ixti)
* Fixed HTTPClient adapter. The response header now receives `request_method`, `request_uri`, and `request_query` transferred from request header
Thanks to [trlorenz](https://github.com/trlorenz)
* Query mapper supports nested data structures i.e. `{"first" => [{"two" => [{"three" => "four"}, "five"]}]}`
Thanks to [Alexander Simonov](https://github.com/simonoff)
* Fixed compatibility with latest versions of Excon which don't define `VALID_REQUEST_KEYS` anymore.
Thanks to [Pablo Jairala](https://github.com/davidjairala)
* Request method is always a symbol is request signatures. This fixes the issue of WebMock not matching Typhoeus requests with request method defined as string.
Thanks to [Thorbjørn Hermanse](https://github.com/thhermansen)
* Stubbing instructions which are displayed when no matching stub is found, can be disabled with `Config.instance.show_stubbing_instructions = false`
Thanks to [Mark Lorenz](https://github.com/dapplebeforedawn)
* Notation used for mapping query strings to data structure can be configured i.e. `WebMock::Config.instance.query_values_notation = :subscript`. This allows setting `:flat_array` notation which supports duplicated parameter names in query string.
Thanks to [tjsousa](https://github.com/tjsousa)
## 1.18.0
* Updated dependency on Addressable to versions >= 2.3.6
* Added support for matching uris using RFC 6570 (URI Templates)
uri_template = Addressable::Template.new "www.example.com/{id}/"
stub_request(:any, uri_template)
Thanks to [Max Lincoln](https://github.com/maxlinc)
* Fixed content length calculation for Rack responses with UTF8 body
Thanks to [Oleg Gritsenko](https://github.com/Claster)
* Add missing Curl::Easy aliases
Thanks to [Hwan-Joon Choi](https://github.com/hc5duke)
* HTTP Gem >= 0.6.0 compatibility
Thanks to [Aleksey V. Zapparov](https://github.com/ixti)
* Minitest 4 and 5 compatibility.
Thanks to [SHIBATA Hiroshi](https://github.com/hsbt)
## 1.17.4
* Update matchers for RSpec 3's matcher protocol
Thanks to [Rob Olson](https://github.com/robolson)
## 1.17.3
* Fixed issue with Rack response removing 'Content-Type' header
Thanks to [Bo Jeanes](https://github.com/bjeanes) and [Matthew Conway](https://github.com/mattonrails)
## 1.17.2
* Support for chunked responses in Curb
Thanks to [Zachary Belzer](https://github.com/zbelzer)
* Fixed handling of request body passed as a hash to `Typhoeus.post`
Thanks to [Mason Chang](https://github.com/changmason) for reporting.
## 1.17.1
* Added missing license statements.
Thanks to [Praveen Arimbrathodiyil](https://github.com/pravi)
## 1.17.0
* HTTP gem support!
Thanks to [Aleksey V. Zapparov](https://github.com/ixti)
* Limited Excon gem requirement to version < 0.30 until the compatibility with version > 0.30.0 is fixed.
Thanks to [Aleksey V. Zapparov](https://github.com/ixti)
* Fixed issue where empty query key caused a `TypeError`
Thanks to [Jon Rowe](https://github.com/JonRowe)
* Handling Typhoeus `on_headers` and `on_body` params.
Thanks to [Matt Burke](https://github.com/spraints)
## 1.16.1
* Fixed "NameError: uninitialized constant WebMock::Response::Pathname" issue.
Thanks to [Alex Stupakow and Karen Wang](https://github.com/stupakov) for the fix.
## 1.16.0
* Allow a Pathname to be passed as a Response body
stub_request(:get, /example.com/).to_return(
body: Rails.root.join('test/fixtures/foo.txt')
)
Thanks to [Ben Pickles](https://github.com/benpickles)
* `hash_including` matcher can be initialized with empty keys to match any values.
stub_request(:post, "www.example.com").with(:body => hash_including(:a, :b => {'c'}))
RestClient.post('www.example.com', '{"a":"1","b":"c"}', :content_type => 'application/json')
Thanks to [Stefano Uliari](https://github.com/steookk)
## 1.15.2
* Fixed `hash_including` to accept a splat of solitary keys.
Thanks to [Tamir Duberstein](https://github.com/tamird) and [https://github.com/strongriley](https://github.com/strongriley)
## 1.15.0
* Excon >= 0.27.5 compatibility.
Thanks to [Brian D. Burns](https://github.com/burns)
## 1.14.0
* Handling non UTF-8 characters in query params.
Thanks to [Florian Dütsch](https://github.com/der-flo) for reporting the issue.
* Added support for `request_block` param in Excon
Thanks to [Dmitry Gutov](https://github.com/dgutov) for reporting the issue.
* Fixed compatibility with latest Curb
Thanks to [Ian Lesperance](https://github.com/elliterate) and [Matthew Horan](https://github.com/mhoran)
* Triggering errbacks assynchronously in em-http-request adapter.
Thanks to [Ian Lesperance](https://github.com/elliterate) and [Matthew Horan](https://github.com/mhoran)
* Handling query params with a hashes nested inside arrays.
Thanks to [Ian Asaff](https://github.com/montague)
* Changed NetConnectNotAllowedError to inherit from Exception to allow it to bubble up into a test suite.
Thanks to [Daniel van Hoesel](https://github.com/s0meone)
* HTTPClient adapter is thread safe.
Thanks to [Tom Beauvais](https://github.com/tbeauvais)
## 1.13.0
* Net::HTTP::Persistent compatibility.
WebMock doesn't disconnect previously started connections upon a request anymore.
## 1.12.3
* Fixed issue with handling Addressable::URI with query params passed to `Net::HTTP.get_response`
Thanks to [Leif Bladt](https://github.com/leifbladt)
* Fixed HTTPClient adapter to not raise an error if a request with multipart body is executed.
## 1.12.2
* Fixed issue with handling request.path when Addressable::URI is passed to #request instead of URI with Ruby 2.0.
Thanks to [Leif Bladt](https://github.com/leifbladt)
* Accept integers as query param values in request stubs
i.e. `stub_request(:get, /.*/).with(:query => {"a" => 1})`
Thanks to [Mitsutaka Mimura](https://github.com/takkanm)
## 1.12.1
* Fixed Minitest < 5.0 compatibility
Thanks to [Alex Tomlins](https://github.com/alext) for reporting the issue.
## 1.12.0
* Not using Gem spec anymore to check loaded Curb version.
* `WebMock.disable_net_connect!` now accepts array of regexps as allow param:
i.e. `WebMock.disable_net_connect!(:allow => [/google.com/, /yahoo.com/])`
Thanks to [Bastien Vaucher](https://github.com/bastien)
* Fixed `on_header` Curb callback behaviour in Curb adapter
Thanks to [Joel Chippindale](https://github.com/mocoso)
* Fixed aws-sdk compatibility with Ruby 2.0, by supporting `continue_timeout` accessor on Net::HTTP socket.
Thanks to [Lin Jen-Shin](https://github.com/godfat)
* Fixed WebMock::Server to not give "log writing failed. can't be called from trap context" warning with Ruby 2.0
Thanks to [Murahashi Sanemat Kenichi](https://github.com/sanemat)
* Added support for EM-HTTP-Request streaming data off disk feature.
Thanks to [Lin Jen-Shin](https://github.com/godfat)
* Added compatibility with Minitest 5
Thanks to [Tim Kurvers](https://github.com/timkurvers)
* Excon >= 0.22 compatibility.
* README has nice sytnax hightlighting and fixed code styling!
Thanks to [Ilya Vassilevsky](https://github.com/vassilevsky)
* Compatibility with Rails 4 `rack.session.options`
Thanks to [gotwalt](https://github.com/gotwalt)
## 1.11.0
* Excon >= 0.17 support.
Thanks to [Nathan Sutton](https://github.com/nate) for reporting this issue and to [Wesley Beary](https://github.com/geemus) and [Myron Marston](https://github.com/myronmarston) for help.
## 1.10.2
* '+' in request path is treated as plus, but in query params always as a space.
## 1.10.1
* '+' in request body is still treated as a space. This fixes a bug introduced in previous version.
Thanks to [Erik Michaels-Ober](https://github.com/sferik) for reporting this problem.
* Fixed issue: response body declared as Proc was not evaluated again on subsequent requests.
Thanks to [Rick Fletcher](https://github.com/rfletcher) for reporting this issue.
## 1.10.0
* '+' in query params is not treated as space anymore and is encoded as %2B
Thanks to [goblin](https://github.com/goblin) for reporting this issue.
* added `remove_request_stub` method to the api to allow removing unused stubs i.e.
stub_get = stub_request(:get, "www.example.com")
remove_request_stub(stub_get)
* `assert_requested` and `assert_not_requested` raise an error if a stub object is provided together with a block.
## 1.9.3
* Fixed issue with unavailable constant Mutex in Ruby < 1.9
Thanks to [Lucas Dohmen](https://github.com/moonglum) for reporting this issue.
## 1.9.2
* Added support for Excon's :response_block parameter
Thanks to [Myron Marston](https://github.com/myronmarston) for reporting this issue.
## 1.9.1
* Fix 'rack.errors' not being set for Rack apps
Thanks to [Alex Grant](https://github.com/grantovich)
* Added support for minitest assertions count
Thanks to [Mokevnin Kirill](https://github.com/mokevnin)
* Fixed issues with registering http requests in multi-threaded environments
Thanks to [Tom Beauvais](https://github.com/tbeauvais)
* Bumped Crack version to >=0.3.2
Thanks to [Jake Benilov](https://github.com/benilovj)
* Fixed issues in Typhoeus 0.6. Defaulted method to GET when no method specified.
Thanks to [Hans Hasselberg](https://github.com/i0rek)
* Add license information to the gemspec
Thanks to [Jordi Massaguer Pla](https://github.com/jordimassaguerpla) and [Murahashi Sanemat Kenichi](https://github.com/sanemat)
* Added support for :expects option in Excon adapter
Thanks to [Evgeniy Dolzhenko](https://github.com/dolzenko)
* Fixed Faye compatibility by treating StringIO in Net::HTTP adapter properly
Thanks to [Pavel Forkert](https://github.com/fxposter)
* Updated VCR link
Thanks to [Rex Feng](https://github.com/xta)
## 1.9.0
* Added support for Typhoeus >= 0.5.0 and removed support for Typhoeus < 0.5.0.
Thanks to [Hans Hasselberg](https://github.com/i0rek)
## 1.8.11
* Fix excon adapter to handle `:body => some_file_object`
Thanks to [Myron Marston](https://github.com/myronmarston)
## 1.8.10
* em-http-request fix. After request callbacks are correctly invoked for 3xx responses,
when :redirects option is set.
Thanks to [Myron Marston](https://github.com/myronmarston) for reporting that issue.
* Fixed compatibility with Net::HTTP::DigestAuth
Thanks to [Jonathan Hyman](https://github.com/jonhyman) for reporting that issue.
* Fixed problem in em-http-request 0.x appending the query to the client URI twice.
Thanks to [Paweł Pierzchała](https://github.com/wrozka)
## 1.8.9
* Fixed problem with caching nil responses when the same HTTPClient instance is used.
Thanks to [Myron Marston](https://github.com/myronmarston)
* Added support for Addressable >= 2.3.0. Addressable 2.3.0 removed support for multiple query value notations and broke backwards compatibility.
https://github.com/sporkmonger/addressable/commit/f51e290b5f68a98293327a7da84eb9e2d5f21c62
https://github.com/sporkmonger/addressable/issues/77
## 1.8.8
* Fixed Net::HTTP adapter so that it returns `nil` for an empty body response.
Thanks to [Myron Marston](https://github.com/myronmarston)
* Gemspec defines compatibility with Addressable ~> 2.2.8, not >= 2.3.0
* Specs compatibility with Typhoeus 0.4.0
Thanks to [Hans Hasselberg](https://github.com/i0rek)
* Handling content types that specify a charset
Thanks to [Kevin Glowacz](https://github.com/kjg)
* Fixed em-http-request adapter to correctly fetch authorization header from a request
Thanks to [Julien Boyer](https://github.com/chatgris)
* Fixing travis-ci image to report master's status
Thanks to [Ryan Schlesinger](https://github.com/ryansch)
* Fixed problem with em-http-request callback triggering if there were other EM::Deferred callbacks registered
Thanks to [Jon Leighton](https://github.com/jonleighton)
* Fixed problem with em-http-request appending the query to the URI a second time, and
the parameters are repeated.
Thanks to [Jon Leighton](https://github.com/jonleighton)
## 1.8.7
* Compatibility with RSpec >= 2.10
Thanks to [erwanlr](https://github.com/erwanlr) for reporting this issue.
* Add missing required rack environment variable SCRIPT_NAME
Thanks to [Eric Oestrich](https://github.com/oestrich)
* Fixed warnings due to @query_params not being initialized
Thanks to [Ben Bleything](https://github.com/bleything)
## 1.8.6
* Pass through SERVER_PORT when stubbing to rack
Thanks to [Eric Oestrich](https://github.com/oestrich)
* Fixed problem with missing parenthesis in `WebMock#net_connect_allowed?` conditions.
Thanks to [aindustries](https://github.com/aindustries)
## 1.8.5
* WebMock::RackResponse supports basic auth
Thanks to [jugyo](https://github.com/jugyo)
## 1.8.4
* Warning message is printed when an unsupported version of a http library is loaded.
Thanks to [Alexander Staubo](https://github.com/alexstaubo) for reporting the problem and to [Myron Marston](https://github.com/myronmarston) for a help with solution.
## 1.8.3
* Fixed compatibility with latest em-http-request
Thanks to [Paul Cortens](https://github.com/thoughtless)
## 1.8.2
* Prevent Webmock `hash_including` from overriding RSpec version 1 `hash_including` method.
Thanks to [Joe Karayusuf](https://github.com/karayusuf)
* Ensured WebMock handles RSpec 1 `hash_including` matcher for matching query params and body.
## 1.8.1
* Ensured WebMock doesn't interfere with `em-synchrony`, when `em-synchrony/em-http` is not included.
Thanks to [Nick Recobra](https://github.com/oruen)
* Improved README
Thanks to [Jordan Elver](https://github.com/jordelver)
## 1.8.0
* Matching request body against partial hash.
stub_http_request(:post, "www.example.com").
with(:body => hash_including({:data => {:a => '1', :b => 'five'}}))
RestClient.post('www.example.com', "data[a]=1&data[b]=five&x=1",
:content_type => 'application/x-www-form-urlencoded') # ===> Success
request(:post, "www.example.com").
with(:body => hash_including({:data => {:a => '1', :b => 'five'}}),
:headers => 'Content-Type' => 'application/json').should have_been_made # ===> Success
Thanks to [Marnen Laibow-Koser](https://github.com/marnen) for help with this solution
* Matching request query params against partial hash.
stub_http_request(:get, "www.example.com").with(:query => hash_including({"a" => ["b", "c"]}))
RestClient.get("http://www.example.com/?a[]=b&a[]=c&x=1") # ===> Success
request(:get, "www.example.com").
with(:query => hash_including({"a" => ["b", "c"]})).should have_been_made # ===> Success
* Added support for Excon.
Thanks to [Dimitrij Denissenko](https://github.com/dim)
* Added support for setting expectations on the request stub with `assert_requested`
stub_get = stub_request(:get, "www.example.com")
stub_post = stub_request(:post, "www.example.com")
Net::HTTP.get('www.example.com', '/')
assert_requested(stub_get)
assert_not_requested(stub_post)
Thanks to [Nicolas Fouché](https://github.com/nfo)
* `WebMock.disable_net_connect!` accepts `RegExp` as `:allow` parameter
Thanks to [Frank Schumacher](https://github.com/thenoseman)
* Ensure multiple values for the same header can be recorded and played back
Thanks to [Myron Marston](https://github.com/myronmarston)
* Updated dependency on Addressable to version >= 2.2.7 to handle nested hash query values. I.e. `?one[two][three][]=four&one[two][three][]=five`
* Fixed compatibility with Curb >= 0.7.16 This breaks compatibility with Curb < 0.7.16
* Fix #to_rack to handle non-array response bodies.
Thanks to [Tammer Saleh](https://github.com/tsaleh)
* Added `read_timeout` accessor to StubSocket which fixes compatibility with aws-sdk
Thanks to [Lin Jen-Shin](https://github.com/godfat)
* Fix warning "instance variable @query_params not initialized"
Thanks to [Joe Van Dyk](https://github.com/joevandyk)
* Using bytesize of message instead of its length for content-length header in em-http-request adapter.
This fixes a problem with messages getting truncated in Ruby >= 1.9
Thanks to [Mark Abramov](https://github.com/markiz)
* Fixed problem with body params being matched even if params were different.
Thanks to [Evgeniy Dolzhenko](https://github.com/dolzenko) for reporting this issue.
## 1.7.10
* Yanked 1.7.9 and rebuilt gem on 1.8.7 to deal with syck/psych incompatibilties in gemspec.
## 1.7.9
* Fixed support for native Typhoeus timeouts.
Thanks to [Albert Llop](https://github.com/mrsimo)
* Fixed problem with WebMock and RSpec compatibility on TeamCity servers. See [this article](http://www.coding4streetcred.com/blog/post/Issue-RubyMine-31-Webmock-162-and-%E2%80%9CSpecconfigure%E2%80%9D-curse.aspx) for more details.
Thanks to [Christopher Pickslay](https://github.com/chrispix) from [Two Bit Labs](https://github.com/twobitlabs)
## 1.7.8
* Fix each adapter so that it calls a `stub.with` block only once per
request. Previously, the block would be called two or three times per
request [Myron Marston](https://github.com/myronmarston).
## 1.7.7 - RuPy 2011 release
* Passing response object to a block passed to `HTTPClient#do_get_block`. This fixes `HTTPClient.get_content` failures. [issue 130](https://github.com/bblimke/webmock/pull/130)
Thanks to [Chris McGrath](https://github.com/chrismcg)
* Cleaned up ruby warnings when running WebMock code with `-w`.
Thanks to [Stephen Celis](https://github.com/stephencelis)
* Curb adapter now correctly calls on_failure for 4xx response codes.
Thanks to [Eugene Pimenov](https://github.com/libc)
## 1.7.6
* Support for the HTTPClient's request_filter feature
Thanks to [Roman Shterenzon](https://github.com/romanbsd)
## 1.7.5
* Added support for Patron 0.4.15. This change is not backward compatible so please upgrade Patron to version >= 0.4.15 if you want to use it with WebMock.
Thanks to [Andreas Garnæs](https://github.com/andreas)
## 1.7.4
* Added support for matching EM-HTTP-Request requests with body declared as a Hash
Thanks to [David Yeu](https://github.com/daveyeu)
## 1.7.3
* Added `Get`, `Post`, `Delete`, `Put`, `Head`, `Option` constants to replaced `Net::HTTP` to make it possible to marshal objects with these constants assigned to properties. This fixed problem with `tvdb_party` gem which serializes HTTParty responses.
Thanks to [Klaus Hartl](https://github.com/carhartl) for reporting this issue.
## 1.7.2
* Redefined `const_get` and `constants` methods on the replaced `Net::HTTP` to return same values as original `Net::HTTP`
## 1.7.1
* Redefined `const_defined?` on the replaced `Net::HTTP` so that it returns true if constant is defined on the original `Net::HTTP`. This fixes problems with `"Net::HTTP::Get".constantize`.
Thanks to [Cássio Marques](https://github.com/cassiomarques) for reporting the issue and to [Myron Marston](https://github.com/myronmarston) for help with the solution.
## 1.7.0
* Fixed Net::HTTP adapter to not break normal Net::HTTP behaviour when network connections are allowed. This fixes **selenium-webdriver compatibility**!!!
* Added support for EM-HTTP-Request 1.0.x and EM-Synchrony. Thanks to [Steve Hull](https://github.com/sdhull)
* Added support for setting expectations to on a stub itself i.e.
stub = stub_request(:get, "www.example.com")
# ... make requests ...
stub.should have_been_requested
Thanks to [Aidan Feldman](https://github.com/afeld)
* Minitest support! Thanks to [Peter Higgins](https://github.com/phiggins)
* Added support for Typhoeus::Hydra
* Added support for `Curb::Easy#http_post` and `Curb::Easy#http_post` with multiple arguments. Thanks to [Salvador Fuentes Jr](https://github.com/fuentesjr) and [Alex Rothenberg](https://github.com/alexrothenberg)
* Rack support. Requests can be stubbed to respond with a Rack app i.e.
class MyRackApp
def self.call(env)
[200, {}, ["Hello"]]
end
end
stub_request(:get, "www.example.com").to_rack(MyRackApp)
RestClient.get("www.example.com") # ===> "Hello"
Thanks to [Jay Adkisson](https://github.com/jayferd)
* Added support for selective disabling and enabling of http lib adapters
WebMock.disable! #disable WebMock (all adapters)
WebMock.disable!(:except => [:net_http]) #disable WebMock for all libs except Net::HTTP
WebMock.enable! #enable WebMock (all adapters)
WebMock.enable!(:except => [:patron]) #enable WebMock for all libs except Patron
* The error message on an unstubbed request shows a code snippet with body as a hash when it was in url encoded form.
> RestClient.post('www.example.com', "data[a]=1&data[b]=2", :content_type => 'application/x-www-form-urlencoded')
WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled....
You can stub this request with the following snippet:
stub_request(:post, "http://www.example.com/").
with(:body => {"data"=>{"a"=>"1", "b"=>"2"}},
:headers => { 'Content-Type'=>'application/x-www-form-urlencoded' }).
to_return(:status => 200, :body => "", :headers => {})
Thanks to [Alex Rothenberg](https://github.com/alexrothenberg)
* The error message on an unstubbed request shows currently registered request stubs.
> stub_request(:get, "www.example.net")
> stub_request(:get, "www.example.org")
> RestClient.get("www.example.com")
WebMock::NetConnectNotAllowedError: Real HTTP connections are disabled....
You can stub this request with the following snippet:
stub_request(:get, "http://www.example.com/").
to_return(:status => 200, :body => "", :headers => {})
registered request stubs:
stub_request(:get, "http://www.example.net/")
stub_request(:get, "http://www.example.org/")
Thanks to [Lin Jen-Shin](https://github.com/godfat) for suggesting this feature.
* Fixed problem with matching requests with json body, when json strings have date format. Thanks to [Joakim Ekberg](https://github.com/kalasjocke) for reporting this issue.
* WebMock now attempts to require each http library before monkey patching it. This is to avoid problem when http library is required after WebMock is required. Thanks to [Myron Marston](https://github.com/myronmarston) for suggesting this change.
* External requests can be disabled while allowing selected ports on selected hosts
WebMock.disable_net_connect!(:allow => "www.example.com:8080")
RestClient.get("www.example.com:80") # ===> Failure
RestClient.get("www.example.com:8080") # ===> Allowed.
Thanks to [Zach Dennis](https://github.com/zdennis)
* Fixed syntax error in README examples, showing the ways of setting request expectations. Thanks to [Nikita Fedyashev](https://github.com/nfedyashev)
**Many thanks to WebMock co-maintainer [James Conroy-Finn](https://github.com/jcf) who did a great job maintaining WebMock on his own for the last couple of months.**
## 1.6.4
This is a quick slip release to regenerate the gemspec. Apparently
jeweler inserts dependencies twice if you use the `gemspec` method in
your Gemfile and declare gem dependencies in your gemspec.
https://github.com/technicalpickles/jeweler/issues/154
josevalim:
> This just bit me. I just released a gem with the wrong dependencies
> because I have updated jeweler. This should have been opt-in,
> otherwise a bunch of people using jeweler are going to release gems
> with the wrong dependencies because you are automatically importing
> from the Gemfile.
## 1.6.3
* Update the dependency on addressable to get around an issue in v2.2.5.
Thanks to [Peter Higgins](https://github.com/phiggins).
* Add support for matching parameter values using a regular expression
as well as a string. Thanks to [Oleg M Prozorov](https://github.com/oleg).
* Fix integration with httpclient as the internal API has changed.
Thanks to [Frank Prößdorf](https://github.com/endor).
* Ensure Curl::Easy#content_type is always set. Thanks to [Peter
Higgins](https://github.com/phiggins).
* Fix bug with em-http-request adapter stubbing responses that have a
chunked transfer encoding. Thanks to [Myron
Marston](https://github.com/myronmarston).
* Fix a load of spec failures with Patron, httpclient, and specs that
depended on the behaviour of example.com. Thanks to [Alex
Grigorovich](https://github.com/grig).
## 1.6.2
* Em-http-request adapter sets `last_effective_url` property. Thanks to [Sam Stokes](https://github.com/samstokes).
* Curb adapter supports `Curb::Easy#http_post` and `Curb::Easy#http_put` without arguments (by setting `post_body` or `put_data` beforehand). Thanks to [Eugene Bolshakov](https://github.com/eugenebolshakov)
## 1.6.1
* Fixed issue with `webmock/rspec` which didn't load correctly if `rspec/core` was already required but `rspec/expectations` not.
## 1.6.0
* Simplified integration with Test::Unit, RSpec and Cucumber. Now only a single file has to be required i.e.
require 'webmock/test_unit'
require 'webmock/rspec'
require 'webmock/cucumber'
* The error message on unstubbed request now contains code snippet which can be used to stub this request. Thanks to Martyn Loughran for suggesting this feature.
* The expectation failure message now contains a list of made requests. Thanks to Martyn Loughran for suggesting this feature.
* Added `WebMock.print_executed_requests` method which can be useful to find out what requests were made until a given point.
* em-http-request adapter is now activated by replacing EventMachine::HttpRequest constant, instead of monkeypatching the original class.
This technique is borrowed from em-http-request native mocking module. It allows switching WebMock adapter on an off, and using it interchangeably with em-http-request native mocking i.e:
EventMachine::WebMockHttpRequest.activate!
EventMachine::WebMockHttpRequest.deactivate!
Thanks to Martyn Loughran for suggesting this feature.
* `WebMock.reset_webmock` is deprecated in favour of new `WebMock.reset!`
* Fixed integration with Cucumber. Previously documented example didn't work with new versions of Cucumber.
* Fixed stubbing requests with body declared as a hash. Thanks to Erik Michaels-Ober for reporting the issue.
* Fixed issue with em-http-request adapter which didn't work when :query option value was passed as a string, not a hash. Thanks to Chee Yeo for reporting the issue.
* Fixed problem with assert_requested which didn't work if used outside rspec or test/unit
* Removed dependency on json gem
## 1.5.0
* Support for dynamically evaluated raw responses recorded with `curl -is`