ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/ 0000755 0001750 0001750 00000000000 13141466106 017024 5 ustar boutil boutil ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/LICENSE.txt 0000644 0001750 0001750 00000002111 13141466106 020642 0 ustar boutil boutil Copyright 2006-2010 Blaine Cook, Chris Kampmeier, and other contributors
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.
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/CHANGELOG 0000644 0001750 0001750 00000022207 13141466106 020241 0 ustar boutil boutil fakeweb (master branch pending release)
* fix a variety of NoMethodErrors when Net::HTTP#read_timeout= or
Net::HTTP#continue_timeout= is called after a Net::HTTP object has handled a
first fake request under newer versions of Ruby and/or some gems (Mechanize,
aws-sdk, etc.) [Marcel Massana, Trevor Rowe, Chris Kampmeier]
* add ability to accept a StringIO as a fake response body
[Larry Diehl, Andy Delcambre, Chris Kampmeier]
* fix an exception when an IO is passed in as a fake response body
[Chris Kampmeier]
* stub responses with no bodies (e.g. to a HEAD request) now return nil for
#body, not an empty string, to match Net::HTTP's behavior [Myron Marston]
* fix warnings on post-1.8 versions of Ruby [Peter Hellberg, Kenichi Kamiya]
* fix that the options hash passed to FakeWeb.register_uri would sometimes be
modified [Chris Kampmeier]
* raise an ArgumentError when FakeWeb.register_uri's third argument can't be
handled as an options hash [David Cornu, Josef Strzibny, Chris Kampmeier]
* raise the more-specific ArgumentError instead of StandardError when the object
passed to FakeWeb.register_uri's :response option can't be handled; this
should be relatively backwards-compatible because ArgumentError descends from
StandardError [Chris Kampmeier]
* deprecation warnings now detect the caller more robustly to work with JRuby's
backtraces [Chris Kampmeier]
fakeweb (1.3.0)
* improve response header registration so you can pass an array to set a header
more than once [Myron Marston]
* fix an exception when the response's :body option was set to nil [Chris Zingel]
* fix that stubbed requests weren't mutating the Net::HTTP request object to set
the body and content-length, like real requests do [Chris Kampmeier]
* add FakeWeb.last_request [Chris Kampmeier]
* assigning a String or Regexp to FakeWeb.allow_net_connect= sets a whitelist
for outbound requests [Dan Dofter, Tim Carey-Smith, Ben Woosley]
fakeweb (1.2.8)
* support Pathname objects where a filename is expected [Chris Kampmeier]
* fix compatibility with Ruby 1.9.2 [Chris Kampmeier]
* simplify storage of FakeWeb::VERSION [Josh Peek, Woody Peterson, Ben Woosley]
fakeweb (1.2.7)
* revert to sorting query params before matching requests against regexps,
instead of the 1.2.6 behavior that tried every possible order combination;
that was factorial-time, which made matching hang for requests with long query
strings [Jason Wadsworth, David Dollar, Blaine Cook]
* print a warning when FakeWeb is loaded before RightHttpConnection or after
Samuel, other libs that patch Net::HTTP [Chris Kampmeier, Ben Brinckerhoff]
fakeweb (1.2.6)
* fix that query params in a regex would have to be sorted for it to ever match
a request URI [Chris Kampmeier, Ben Hall]
* improve regex handling so registration with an explicit port (like
/example.com:80/) matches a request that uses an implied port
(like "http://example.com/") [Chris Kampmeier, Dan Dofter]
* refactor URI registry to reduce duplication; now about twice as fast at
handling requests [Chris Kampmeier]
* Add FakeWeb::VERSION so you can programmatically determine what version of
FakeWeb is loaded without using RubyGems [Chris Kampmeier, Chris Wanstrath]
fakeweb (1.2.5)
* fix handling of userinfo strings that contain percent-encoded unsafe
characters [Chris Kampmeier, Ken Mayer]
* fix that exact matches against strings/URIs with the :any method had a lower
precedence than regex matches using a real HTTP method (exact matches now
always take precedence) [Chris Kampmeier]
* change request handling to raise an exception when more than one registered
regex matches a request URI [Chris Kampmeier]
fakeweb (1.2.4)
* add experimental support for matching URIs via regular expressions
[Jacqui Maher, Tiago Albineli Motta, Peter Wagene]
* fix an exception when registering with the :response option and a string that
is the same as the name of a directory in the current path [Chris Kampmeier]
* DEPRECATION: Calling FakeWeb.register_uri with a :string or :file option is
now deprecated. Both options have been replaced with a unified :body option,
since they supply the response body (as opposed to :response, which supplies
the full response including headers) [Chris Kampmeier]
* add support for specifying HTTP headers as options to FakeWeb.register_uri
when using the :string or :file response types, since those methods only
specify a response body [David Michael, Chris Kampmeier]
* DEPRECATION: Calling FakeWeb.register_uri and FakeWeb.registered_uri? without
an HTTP method as the first argument is now deprecated. To match against any
HTTP method (the pre-1.2.0 behavior), use :any [Chris Kampmeier]
fakeweb (1.2.3)
* fix the #http_version of :file and :string responses, which was returning the
request URI instead of something sensible like "1.0" [Chris Kampmeier]
* add method aliases in the Net::HTTP patch to eliminate warnings when running
with -w [Joshua Clingenpeel]
* fix that removing the redefinition of OpenURI::HTTPError in 1.2.0 caused
:exception responses to raise when OpenURI isn't available [Chris Kampmeier]
* fix registering an :exception response with classes that require arguments for
instantiation, like Interrupt's subclasses [Chris Kampmeier]
fakeweb (1.2.2)
* fix that HTTP Digest and OAuth requests could raise URI::InvalidURIErrors
[Bill Kocik, Chris Kampmeier]
fakeweb (1.2.1)
* fix that query parameters are handled correctly when registering with a URI
object [Anselmo Alves, Chris Kampmeier]
* fix an exception when registering with the :response option and a string
containing "\0" [Jonathan Baudanza, Chris Kampmeier]
* fix that trailing slashes were considered significant for requests to the root
of a domain [Chris Kampmeier]
* add support for HTTP basic authentication via userinfo strings in URIs
[Michael Bleigh]
fakeweb (1.2.0)
* add lib/fakeweb.rb so you can require "fakeweb" as well [Chris Kampmeier]
* fix compatibility with Ruby 1.9.1 [Chris Kampmeier]
* fix that newlines in file-based responses could be doubled in the response
object's body [Mark Menard, Chris Kampmeier]
* fix unnecessary munging of the transfer-encoding header, which improves
compatibility with mechanize [Mark Menard]
* fix a test and the RCov dependency to be compatible with JRuby [Mark Menard]
* remove an unnecessary redefinition of OpenURI::HTTPError [Josh Nichols]
* rearrange implementation code into separate files, one per class [Josh Nichols]
* fix a bug where FakeWeb.response_for would raise if the request wasn't
registered [Chris Kampmeier]
* add HTTP method support, so FakeWeb takes both the URI and method into
account for registration, requests, and responses. Backwards-compatible with
the old method signatures, which didn't have a method param. [Chris Kampmeier]
* start work on Ruby 1.9 compatibility [Chris Kampmeier]
* add FakeWeb.allow_net_connect= to enable/disable the pass-through to
Net::HTTP for unregistered URIs [Mislav Marohnić, Chris Kampmeier]
* remove setup.rb, since most people use RubyGems [Mislav Marohnić]
* fix that 'http://example.com/?' (empty query) matches a registered
'http://example.com/', and vice-versa [Mislav Marohnić]
* improve the test suite to not rely on an internet connection [Chris Kampmeier]
* use `rake test` instead of `rake tests` [Josh Nichols]
* fix an incompatibility with Ruby 1.8.6 p36 where you'd get "Errno::EINTR:
Interrupted system call" exceptions in Socket#sysread for any non-faked
request [Chris Kampmeier]
* response rotation: you can now optionally call FakeWeb.register_uri with an
array of options hashes; these are used, in order, to respond to
repeated requests (to repeat a response more than once before rotating, use
the :times option). Once you run out of responses, further requests always
receive the last response. [Michael Shapiro]
* add support for Net::HTTP's undocumented full-URI request style (fixes
URI::InvalidURIErrors that you might see in older libraries) [Chris Kampmeier]
* sort query params before storing internally, so that
http://example.com/?a=1&b=2 and http://example.com/?b=2&a=1 are considered the
same URL (although this is technically incorrect, it's much more
convenient--most web apps work that way, and Net::HTTP's use of a hash to pass
query params means that the order in which FakeWeb stores them can be
unpredictable) [Chris Kampmeier]
* add support for ports in URLs, so that http://example.com/ and
http://example.com:3000/ are not the same [Chris Kampmeier]
* fix for non-faked SSL requests failing with "Unable to create local socket"
[Chris Kampmeier]
* update Rakefile to fix warning about deprecated code [Chris Kampmeier]
fakeweb (1.1.2)
* add required dependencies to GemSpec to ensure that tests pass in firebrigade
(http://firebrigade.seattlerb.org/) [Blaine Cook]
fakeweb (1.1.1)
* fix for non-existence of :string method on File as presented by open-uri
[Blaine Cook]
* fix for curl example test - google redirects to ccTLDs for those outside US
[Blaine Cook]
fakeweb (1.1.0)
* update code to correspond to ruby 1.8.4 (breaks compatibility with ruby 1.8.2)
[Blaine Cook]
fakeweb (1.0.0)
* initial import [Blaine Cook]
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/.gitignore 0000644 0001750 0001750 00000000110 13141466106 021004 0 ustar boutil boutil /doc
/rdoc
/html
/coverage
/log
/pkg
/.bundle
/.idea
*.rbc
Gemfile.lock
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/.travis.yml 0000644 0001750 0001750 00000000341 13141466106 021133 0 ustar boutil boutil language: ruby
rvm:
- 1.8.7
- ree
- 1.9.2
- 1.9.3
- 2.0.0
- ruby-head
- jruby-18mode
- jruby-19mode
- jruby-head
- rbx
before_install: gem install bundler --conservative --version '~> 1.3' --no-prerelease
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/.autotest 0000644 0001750 0001750 00000001277 13141466106 020704 0 ustar boutil boutil require 'autotest/bundler'
require 'autotest/restart'
# Let child processes know that they're running under autotest,
# so they can disable test-coverage reporting, etc.
ENV["AUTOTEST"] = "1"
Autotest.add_hook :initialize do |autotest|
autotest.order = :random
%w(.git coverage log vendor).each do |directory|
autotest.add_exception(directory)
end
# Our tests are fast enough that it's reasonable to just run 'em all
# whenever something changes
autotest.clear_mappings
autotest.add_mapping /^Gemfile|^Rakefile|\.gemspec$|\.rb$/ do
autotest.files_matching %r|^test/test_\w+\.rb$|
end
end
Autotest.add_hook :run_command do |at|
system "bundle exec rake test:preflight"
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/ 0000755 0001750 0001750 00000000000 13252215206 017777 5 ustar boutil boutil ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_registering_with_io.rb 0000644 0001750 0001750 00000006041 13141466106 025434 0 ustar boutil boutil require 'test_helper'
class TestRegisteringWithIO < Test::Unit::TestCase
def test_registering_a_file_handle_without_transfer_encoding
file = File.new(fixture_path("google_response_without_transfer_encoding"))
FakeWeb.register_uri(:get, "http://google.com", :response => file)
response = Net::HTTP.start("google.com") { |query| query.get('/') }
assert response.body.include?("
Google")
end
def test_registering_a_file_handle_with_transfer_encoding
file = File.new(fixture_path("google_response_with_transfer_encoding"))
FakeWeb.register_uri(:get, "http://google.com", :response => file)
response = Net::HTTP.start("google.com") { |query| query.get('/') }
assert response.body.include?("Google")
end
def test_registering_a_file_handle_from_curl
file = File.new(fixture_path("google_response_from_curl"))
FakeWeb.register_uri(:get, "http://google.com", :response => file)
response = Net::HTTP.start("google.com") { |query| query.get('/') }
assert response.body.include?("Google")
end
def test_registering_a_stringio
stringio = StringIO.new(File.read(fixture_path("google_response_from_curl")))
FakeWeb.register_uri(:get, "http://google.com", :response => stringio)
response = Net::HTTP.start("google.com") { |query| query.get('/') }
assert response.body.include?("Google")
end
def test_creating_net_buffered_io_directly_with_an_unsupported_underlying_object
# It's not possible to exercise this code path through an end-user API because
# FakeWeb::Responder performs an equivalent check on the object before passing
# it on to Net::BufferedIO. So this is just an internal sanity check.
string = ""
Net::BufferedIO.new(string)
stringio = StringIO.new(File.read(fixture_path("google_response_from_curl")))
Net::BufferedIO.new(stringio)
unsupported = Time.now
assert_raises ArgumentError do
Net::BufferedIO.new(unsupported)
end
end
def test_creating_net_buffered_io_with_ruby_24_method_signature
# These keyword arguments were added to BufferedIO.new's params in Ruby 2.4
call_with_keyword_args = lambda do
eval <<-RUBY
Net::BufferedIO.new("", read_timeout: 1, continue_timeout: 1, debug_output: nil)
RUBY
end
if RUBY_VERSION >= "2.4.0"
# Should not raise
call_with_keyword_args.call
elsif RUBY_VERSION >= "2.0.0"
# From Ruby 2.0 to 2.3, keyword arguments are generally valid syntax, but
# had not been added to BufferedIO.new's method signature
assert_raises(ArgumentError) { call_with_keyword_args.call }
elsif RUBY_VERSION >= "1.9.0"
# Ruby 1.9 will interpret the arguments as a new-style options hash,
# which is also not in the method signature
assert_raises(ArgumentError) { call_with_keyword_args.call }
else
# Ruby 1.8 won't know how to parse this, since it had neither new-style
# hashes nor keyword arguments
assert_raises(SyntaxError) { call_with_keyword_args.call }
end
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_last_request.rb 0000644 0001750 0001750 00000002263 13141466106 024105 0 ustar boutil boutil require 'test_helper'
class TestLastRequest < Test::Unit::TestCase
def test_last_request_returns_correct_net_http_request_class
FakeWeb.register_uri(:get, "http://example.com", :status => [200, "OK"])
Net::HTTP.start("example.com") { |http| http.get("/") }
assert_instance_of Net::HTTP::Get, FakeWeb.last_request
end
def test_last_request_has_correct_method_path_and_body_for_get
FakeWeb.register_uri(:get, "http://example.com", :status => [200, "OK"])
Net::HTTP.start("example.com") { |http| http.get("/") }
assert_equal "GET", FakeWeb.last_request.method
assert_equal "/", FakeWeb.last_request.path
assert_nil FakeWeb.last_request.body
assert_nil FakeWeb.last_request.content_length
end
def test_last_request_has_correct_method_path_and_body_for_post
FakeWeb.register_uri(:post, "http://example.com/posts", :status => [201, "Created"])
Net::HTTP.start("example.com") { |http| http.post("/posts", "title=Test") }
assert_equal "POST", FakeWeb.last_request.method
assert_equal "/posts", FakeWeb.last_request.path
assert_equal "title=Test", FakeWeb.last_request.body
assert_equal 10, FakeWeb.last_request.content_length
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_trailing_slashes.rb 0000644 0001750 0001750 00000004220 13141466106 024720 0 ustar boutil boutil require 'test_helper'
class TestFakeWebTrailingSlashes < Test::Unit::TestCase
def test_registering_root_without_slash_and_ask_predicate_method_with_slash
FakeWeb.register_uri(:get, "http://www.example.com", :body => "root")
assert FakeWeb.registered_uri?(:get, "http://www.example.com/")
end
def test_registering_root_without_slash_and_request
FakeWeb.register_uri(:get, "http://www.example.com", :body => "root")
response = Net::HTTP.start("www.example.com") { |query| query.get('/') }
assert_equal "root", response.body
end
def test_registering_root_with_slash_and_ask_predicate_method_without_slash
FakeWeb.register_uri(:get, "http://www.example.com/", :body => "root")
assert FakeWeb.registered_uri?(:get, "http://www.example.com")
end
def test_registering_root_with_slash_and_request
FakeWeb.register_uri(:get, "http://www.example.com/", :body => "root")
response = Net::HTTP.start("www.example.com") { |query| query.get('/') }
assert_equal "root", response.body
end
def test_registering_path_without_slash_and_ask_predicate_method_with_slash
FakeWeb.register_uri(:get, "http://www.example.com/users", :body => "User list")
assert !FakeWeb.registered_uri?(:get, "http://www.example.com/users/")
end
def test_registering_path_without_slash_and_request_with_slash
FakeWeb.allow_net_connect = false
FakeWeb.register_uri(:get, "http://www.example.com/users", :body => "User list")
assert_raise FakeWeb::NetConnectNotAllowedError do
Net::HTTP.start("www.example.com") { |query| query.get('/users/') }
end
end
def test_registering_path_with_slash_and_ask_predicate_method_without_slash
FakeWeb.register_uri(:get, "http://www.example.com/users/", :body => "User list")
assert !FakeWeb.registered_uri?(:get, "http://www.example.com/users")
end
def test_registering_path_with_slash_and_request_without_slash
FakeWeb.allow_net_connect = false
FakeWeb.register_uri(:get, "http://www.example.com/users/", :body => "User list")
assert_raise FakeWeb::NetConnectNotAllowedError do
Net::HTTP.start("www.example.com") { |query| query.get('/users') }
end
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_precedence.rb 0000644 0001750 0001750 00000007526 13141466106 023476 0 ustar boutil boutil require 'test_helper'
class TestPrecedence < Test::Unit::TestCase
def test_matching_get_strings_have_precedence_over_matching_get_regexes
FakeWeb.register_uri(:get, "http://example.com/test", :body => "string")
FakeWeb.register_uri(:get, %r|http://example\.com/test|, :body => "regex")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "string", response.body
end
def test_matching_any_strings_have_precedence_over_matching_any_regexes
FakeWeb.register_uri(:any, "http://example.com/test", :body => "string")
FakeWeb.register_uri(:any, %r|http://example\.com/test|, :body => "regex")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "string", response.body
end
def test_matching_get_strings_have_precedence_over_matching_any_strings
FakeWeb.register_uri(:get, "http://example.com/test", :body => "get method")
FakeWeb.register_uri(:any, "http://example.com/test", :body => "any method")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "get method", response.body
# registration order should not matter
FakeWeb.register_uri(:any, "http://example.com/test2", :body => "any method")
FakeWeb.register_uri(:get, "http://example.com/test2", :body => "get method")
response = Net::HTTP.start("example.com") { |query| query.get('/test2') }
assert_equal "get method", response.body
end
def test_matching_any_strings_have_precedence_over_matching_get_regexes
FakeWeb.register_uri(:any, "http://example.com/test", :body => "any string")
FakeWeb.register_uri(:get, %r|http://example\.com/test|, :body => "get regex")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "any string", response.body
end
def test_registered_strings_and_uris_are_equivalent_so_second_takes_precedence
FakeWeb.register_uri(:get, "http://example.com/test", :body => "string")
FakeWeb.register_uri(:get, URI.parse("http://example.com/test"), :body => "uri")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "uri", response.body
FakeWeb.register_uri(:get, URI.parse("http://example.com/test2"), :body => "uri")
FakeWeb.register_uri(:get, "http://example.com/test2", :body => "string")
response = Net::HTTP.start("example.com") { |query| query.get('/test2') }
assert_equal "string", response.body
end
def test_identical_registration_replaces_previous_registration
FakeWeb.register_uri(:get, "http://example.com/test", :body => "first")
FakeWeb.register_uri(:get, "http://example.com/test", :body => "second")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "second", response.body
end
def test_identical_registration_replaces_previous_registration_accounting_for_normalization
FakeWeb.register_uri(:get, "http://example.com/test?", :body => "first")
FakeWeb.register_uri(:get, "http://example.com:80/test", :body => "second")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "second", response.body
end
def test_identical_registration_replaces_previous_registration_accounting_for_query_params
FakeWeb.register_uri(:get, "http://example.com/test?a=1&b=2", :body => "first")
FakeWeb.register_uri(:get, "http://example.com/test?b=2&a=1", :body => "second")
response = Net::HTTP.start("example.com") { |query| query.get('/test?a=1&b=2') }
assert_equal "second", response.body
end
def test_identical_registration_replaces_previous_registration_with_regexes
FakeWeb.register_uri(:get, /test/, :body => "first")
FakeWeb.register_uri(:get, /test/, :body => "second")
response = Net::HTTP.start("example.com") { |query| query.get('/test') }
assert_equal "second", response.body
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/helpers/ 0000755 0001750 0001750 00000000000 13141466106 021445 5 ustar boutil boutil ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/helpers/start_simplecov.rb 0000644 0001750 0001750 00000003062 13141466106 025211 0 ustar boutil boutil module FakeWebTestHelper
module CodeCoverage
def start_simplecov
return unless coverage_supported_by_this_ruby?
return if !ENV['AUTOTEST'].nil?
require 'simplecov'
require 'simplecov-console'
SimpleCov.start do
add_filter "/test/"
minimum_coverage 100 if this_process_responsible_for_coverage_reporting?
command_name SIMPLECOV_COMMAND_NAME if child_test_process?
formatter simplecov_formatter_class
coverage_dir "coverage/#{ENV['TEST_ENV_NUMBER']}" if !ENV['TEST_ENV_NUMBER'].nil?
end
end
def simplecov_formatter_class
include SimpleCov::Formatter
formatters = []
if this_process_responsible_for_coverage_reporting?
formatters << Console
formatters << HTMLFormatter if html_report_requested?
end
MultiFormatter.new(formatters)
end
def this_process_responsible_for_coverage_reporting?
running_all_tests? && !child_test_process?
end
def running_all_tests?
ARGV == Dir["test/test_*.rb"] - ["test/test_helper.rb"]
end
def child_test_process?
defined?(SIMPLECOV_COMMAND_NAME)
end
def html_report_requested?
!ENV["COVERAGE_REPORT"].nil?
end
def coverage_supported_by_this_ruby?
return false if defined?(RUBY_ENGINE) && RUBY_ENGINE == "rbx"
# Ruby's built-in Coverage first shipped with Ruby 1.9.0, but SimpleCov
# doesn't work very well on pre-1.9.3.
RUBY_VERSION >= "1.9.3"
end
extend self
end
end
FakeWebTestHelper::CodeCoverage.start_simplecov
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_other_net_http_libraries.rb 0000644 0001750 0001750 00000005203 13141466106 026451 0 ustar boutil boutil require 'test_helper'
# Each of these tests shells out to `ruby -rfakeweb ...` so
# we can see how FakeWeb behaves with different combinations of
# other gems loaded without polluting the rest of our tests.
class TestOtherNetHttpLibraries < Test::Unit::TestCase
def capture_output_from_requiring(libs, additional_code = "")
requires = libs.map { |lib| "require '#{lib}'" }.join("; ")
fakeweb_test_dir = File.dirname(__FILE__)
load_paths = [fakeweb_test_dir,
File.expand_path("#{fakeweb_test_dir}/../lib")]
load_paths += Dir["#{fakeweb_test_dir}/vendor/*/lib"]
load_path_opts = load_paths.map { |dir| "-I#{dir}" }.join(" ")
# Since each test in this class starts a new Ruby process to run
# implementation code, the main test process's Coverage database
# won't know that code's been exercised. Instead, you have to load
# SimpleCov at the start of each process, collect the results as
# they exit, then finally merge them with the original test
# process's stats at the end of the suite. SimpleCov is magic and
# does this for you (!) as long as you inform it re: the haps by
# providing a unique, stable identifier for each part.
# We can just use the name of the current test, since we only
# start one process per test. The original process (comprising
# the rest of the tests) will just get the default name
# "Unit Tests".
simplecov_code = "SIMPLECOV_COMMAND_NAME = '#{current_test_name}'; require 'helpers/start_simplecov'"
output = `#{ruby_path} #{current_ruby_opts.join(' ')} #{load_path_opts} -e "#{simplecov_code}; #{requires}; #{additional_code}" 2>&1`
remove_warnings_from_gems_and_stdlib(output)
end
def test_requiring_samuel_before_fakeweb_prints_warning
output = capture_output_from_requiring %w(samuel fakeweb)
assert_match %r(Warning: FakeWeb was loaded after Samuel), output
end
def test_requiring_samuel_after_fakeweb_does_not_print_warning
output = capture_output_from_requiring %w(fakeweb samuel)
assert_empty output
end
def test_requiring_right_http_connection_before_fakeweb_and_then_connecting_does_not_print_warning
additional_code = "Net::HTTP.start('example.com')"
output = capture_output_from_requiring %w(right_http_connection fakeweb), additional_code
assert_empty output
end
def test_requiring_right_http_connection_after_fakeweb_and_then_connecting_prints_warning
additional_code = "Net::HTTP.start('example.com')"
output = capture_output_from_requiring %w(fakeweb right_http_connection), additional_code
assert_match %r(Warning: RightHttpConnection was loaded after FakeWeb), output
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_missing_pathname.rb 0000644 0001750 0001750 00000002177 13141466106 024724 0 ustar boutil boutil require 'test_helper'
class TestMissingPathname < Test::Unit::TestCase
def setup
super
@saved_pathname = Pathname
Object.send(:remove_const, :Pathname)
end
def teardown
super
Object.const_set(:Pathname, @saved_pathname)
end
# FakeWeb supports using Pathname objects where filenames are expected, but
# Pathname isn't required to use FakeWeb. Make sure everything still works
# when Pathname isn't in use.
def test_register_using_body_without_pathname
FakeWeb.register_uri(:get, "http://example.com/", :body => fixture_path("test_example.txt"))
Net::HTTP.start("example.com") { |http| http.get("/") }
end
def test_register_using_response_without_pathname
FakeWeb.register_uri(:get, "http://example.com/", :response => fixture_path("google_response_without_transfer_encoding"))
Net::HTTP.start("example.com") { |http| http.get("/") }
end
def test_register_using_unsupported_response_without_pathname
FakeWeb.register_uri(:get, "http://example.com/", :response => 1)
assert_raises ArgumentError do
Net::HTTP.start("example.com") { |http| http.get("/") }
end
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_helper.rb 0000644 0001750 0001750 00000015131 13141466106 022647 0 ustar boutil boutil require 'rubygems'
require 'bundler'
Bundler.setup
require 'helpers/start_simplecov'
require 'test/unit'
require 'open-uri'
require 'pathname'
require 'fake_web'
require 'rbconfig'
# See mocha's modifying
# https://github.com/freerange/mocha/commit/6df882d33ba785e0b43b224b7d625841d8e203be#lib/mocha/setup.rb
begin
require 'mocha/setup'
rescue LoadError
require 'mocha'
end
# Give all tests a common setup and teardown that prevents shared state
class Test::Unit::TestCase
alias setup_without_fakeweb setup
def setup
FakeWeb.clean_registry
@original_allow_net_connect = FakeWeb.allow_net_connect?
FakeWeb.allow_net_connect = false
end
alias teardown_without_fakeweb teardown
def teardown
FakeWeb.allow_net_connect = @original_allow_net_connect
end
end
module FakeWebTestHelper
BUILTIN_ASSERTIONS = Test::Unit::TestCase.instance_methods.select { |m| m.to_s =~ /^assert/ }.map { |m| m.to_sym }
# Backport assert_empty for Ruby 1.8 (it comes from MiniTest)
if !BUILTIN_ASSERTIONS.include?(:assert_empty)
def assert_empty(actual, message = nil)
message = build_message(message, "> is not empty", actual)
assert_block message do
actual.empty?
end
end
end
def fixture_path(basename)
"test/fixtures/#{basename}"
end
def capture_stderr
$stderr = StringIO.new
yield
$stderr.rewind && $stderr.read
ensure
$stderr = STDERR
end
# The path to the current ruby interpreter. Adapted from Rake's FileUtils.
def ruby_path
ext = ((RbConfig::CONFIG['ruby_install_name'] =~ /\.(com|cmd|exe|bat|rb|sh)$/) ? "" : RbConfig::CONFIG['EXEEXT'])
File.join(RbConfig::CONFIG['bindir'], RbConfig::CONFIG['ruby_install_name'] + ext).sub(/.*\s.*/m, '"\&"')
end
# Returns the name of the currently-running Test::Unit test method. This
# simply scans the call stack for the first method name starting with
# "test_". (TODO: is there a first-class way to retrieve this in Test::Unit?)
def current_test_name
caller.detect { |line| line =~ /:\d+:in `(test_\w+)'$/ }
$1.to_sym
end
def current_ruby_opts
ruby_opts = []
ruby_opts << "-w" if defined?($-w) && $-w
# Propagate JRuby options needed to measure code coverage. See JRuby's
# util/cli/ArgumentProcessor.java for details.
if RUBY_PLATFORM == "java" &&
JRuby.runtime.instance_config.class.FULL_TRACE_ENABLED &&
JRuby.runtime.instance_config.compile_mode.to_s == "OFF"
ruby_opts << "--debug" << "--dev"
end
ruby_opts
end
def remove_warnings_from_gems_and_stdlib(string)
code_paths = [RbConfig::CONFIG["libdir"],
File.expand_path(File.join(File.dirname(__FILE__), "vendor")),
"./test/vendor",
Gem.path].flatten
splitter = string.respond_to?(:lines) ? :lines : :to_a
string.send(splitter).reject { |line|
line.strip.empty? ||
code_paths.any? { |path| line =~ /^#{Regexp.escape(path)}.+:\d+:? warning:/ }
}.join
end
# Sets several expectations (using Mocha) that a real HTTP request makes it
# past FakeWeb to the socket layer. You can use this when you need to check
# that a request isn't handled by FakeWeb.
def setup_expectations_for_real_request(options = {})
# Socket handling
if options[:port] == 443
socket = mock("SSLSocket")
OpenSSL::SSL::SSLSocket.expects(:===).with(socket).returns(true).at_least_once
OpenSSL::SSL::SSLSocket.expects(:new).with(socket, instance_of(OpenSSL::SSL::SSLContext)).returns(socket).at_least_once
socket.stubs(:sync_close=).returns(true)
# MRI's Net::HTTP switched from stdlib's timeout.rb to an internal
# implementation using io/wait and connect_nonblock in Ruby 2.3.
# See https://github.com/ruby/ruby/commit/bab5bf0c79ba
#
# Although recent versions of Rubinius report themselves as Ruby 2.3,
# they do not yet incorporate this change.
if RUBY_VERSION >= "2.3.0" && RUBY_ENGINE != "rbx"
socket.expects(:connect_nonblock).with(any_parameters).at_least_once
else
socket.expects(:connect).with().at_least_once
end
if RUBY_VERSION >= "2.0.0" && RUBY_PLATFORM != "java"
socket.expects(:session).with().at_least_once
end
else
socket = mock("TCPSocket")
Socket.expects(:===).with(socket).at_least_once.returns(true)
end
# Net::HTTP#connect now sets TCP_NODELAY after opening the socket. See ruby-core:56158.
if RUBY_VERSION >= "2.1.0"
socket.stubs(:setsockopt).returns(0)
end
if RUBY_VERSION >= "2.0.0"
TCPSocket.expects(:open).with(options[:host], options[:port], nil, nil).returns(socket).at_least_once
else
TCPSocket.expects(:open).with(options[:host], options[:port]).returns(socket).at_least_once
end
socket.stubs(:closed?).returns(false)
socket.stubs(:close).returns(true)
# Request/response handling
request_parts = ["#{options[:method]} #{options[:path]} HTTP/1.1", "Host: #{options[:host]}"]
socket.expects(:write).with(all_of(includes(request_parts[0]), includes(request_parts[1]))).returns(100)
if !options[:request_body].nil?
socket.expects(:write).with(options[:request_body]).returns(100)
end
# MRI's Net::HTTP switched from #sysread to #read_nonblock in
# 1.9.2; although subsequent JRuby releases reported version
# numbers later than 1.9.2p0 when running in 1.9-mode, JRuby
# didn't switch until 1.7.4 (a.k.a. 1.9.3p392 in 1.9-mode):
# https://github.com/jruby/jruby/commit/d04857cb0f.
if RUBY_PLATFORM == "java" && ((RUBY_VERSION == "1.9.3" && RUBY_PATCHLEVEL >= 392) || RUBY_VERSION > "1.9.3")
read_method = :read_nonblock
elsif RUBY_PLATFORM != "java" && RUBY_VERSION >= "1.9.2"
read_method = :read_nonblock
else
read_method = :sysread
end
socket.expects(read_method).at_least_once.returns("HTTP/1.1 #{options[:response_code]} #{options[:response_message]}\nContent-Length: #{options[:response_body].length}\n\n#{options[:response_body]}").then.raises(EOFError)
end
# A helper that calls #setup_expectations_for_real_request for you, using
# defaults for our commonly used test request to images.apple.com.
def setup_expectations_for_real_apple_hot_news_request(options = {})
defaults = { :host => "images.apple.com", :port => 80, :method => "GET",
:path => "/main/rss/hotnews/hotnews.rss",
:response_code => 200, :response_message => "OK",
:response_body => "Apple Hot News" }
setup_expectations_for_real_request(defaults.merge(options))
end
end
Test::Unit::TestCase.send(:include, FakeWebTestHelper)
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_query_string.rb 0000644 0001750 0001750 00000003515 13141466106 024126 0 ustar boutil boutil require 'test_helper'
class TestFakeWebQueryString < Test::Unit::TestCase
def test_register_uri_string_with_query_params
FakeWeb.register_uri(:get, 'http://example.com/?a=1&b=1', :body => 'foo')
assert FakeWeb.registered_uri?(:get, 'http://example.com/?a=1&b=1')
FakeWeb.register_uri(:post, URI.parse("http://example.org/?a=1&b=1"), :body => "foo")
assert FakeWeb.registered_uri?(:post, "http://example.org/?a=1&b=1")
end
def test_register_uri_with_query_params_and_check_in_different_order
FakeWeb.register_uri(:get, 'http://example.com/?a=1&b=1', :body => 'foo')
assert FakeWeb.registered_uri?(:get, 'http://example.com/?b=1&a=1')
FakeWeb.register_uri(:post, URI.parse('http://example.org/?a=1&b=1'), :body => 'foo')
assert FakeWeb.registered_uri?(:post, 'http://example.org/?b=1&a=1')
end
def test_registered_uri_gets_recognized_with_empty_query_params
FakeWeb.register_uri(:get, 'http://example.com/', :body => 'foo')
assert FakeWeb.registered_uri?(:get, 'http://example.com/?')
FakeWeb.register_uri(:post, URI.parse('http://example.org/'), :body => 'foo')
assert FakeWeb.registered_uri?(:post, 'http://example.org/?')
end
def test_register_uri_with_empty_query_params_and_check_with_none
FakeWeb.register_uri(:get, 'http://example.com/?', :body => 'foo')
assert FakeWeb.registered_uri?(:get, 'http://example.com/')
FakeWeb.register_uri(:post, URI.parse('http://example.org/?'), :body => 'foo')
assert FakeWeb.registered_uri?(:post, 'http://example.org/')
end
def test_registry_sort_query_params
assert_equal "a=1&b=2", FakeWeb::Registry.instance.send(:sort_query_params, "b=2&a=1")
end
def test_registry_sort_query_params_sorts_by_value_if_keys_collide
assert_equal "a=1&a=2&b=2", FakeWeb::Registry.instance.send(:sort_query_params, "a=2&b=2&a=1")
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_fake_web.rb 0000644 0001750 0001750 00000063074 13141466106 023144 0 ustar boutil boutil require 'test_helper'
class TestFakeWeb < Test::Unit::TestCase
def test_register_uri
FakeWeb.register_uri(:get, 'http://mock/test_example.txt', :body => "example")
assert FakeWeb.registered_uri?(:get, 'http://mock/test_example.txt')
end
def test_register_uri_with_wrong_number_of_arguments
assert_raises ArgumentError do
FakeWeb.register_uri("http://example.com")
end
assert_raises ArgumentError do
FakeWeb.register_uri(:get, "http://example.com", "/example", :body => "example")
end
end
def test_register_uri_with_string_for_third_argument
exception = assert_raises ArgumentError do
FakeWeb.register_uri(:get, "http://example.com", "response")
end
assert_match 'Expected options hash: "response"', exception.message
end
def test_register_uri_with_array_of_strings_for_third_argument
exception = assert_raises ArgumentError do
FakeWeb.register_uri(:get, "http://example.com", ["first response"])
end
assert_match 'Expected options hash: "first response"', exception.message
end
def test_registered_uri_with_wrong_number_of_arguments
assert_raises ArgumentError do
FakeWeb.registered_uri?
end
assert_raises ArgumentError do
FakeWeb.registered_uri?(:get, "http://example.com", "/example")
end
end
def test_response_for_with_wrong_number_of_arguments
assert_raises ArgumentError do
FakeWeb.response_for
end
assert_raises ArgumentError do
FakeWeb.response_for(:get, "http://example.com", "/example")
end
end
def test_register_uri_with_invalid_uri
assert_raises URI::InvalidURIError do
FakeWeb.register_uri(:get, '#~invalid~#', :body => "OK")
end
end
def test_register_uri_with_port_and_check_with_port
FakeWeb.register_uri(:get, 'http://example.com:3000/', :body => 'foo')
assert FakeWeb.registered_uri?(:get, 'http://example.com:3000/')
end
def test_register_uri_with_port_and_check_without_port
FakeWeb.register_uri(:get, 'http://example.com:3000/', :body => 'foo')
assert !FakeWeb.registered_uri?(:get, 'http://example.com/')
end
def test_register_uri_with_default_port_for_http_and_check_without_port
FakeWeb.register_uri(:get, 'http://example.com:80/', :body => 'foo')
assert FakeWeb.registered_uri?(:get, 'http://example.com/')
end
def test_register_uri_with_default_port_for_https_and_check_without_port
FakeWeb.register_uri(:get, 'https://example.com:443/', :body => 'foo')
assert FakeWeb.registered_uri?(:get, 'https://example.com/')
end
def test_register_uri_with_no_port_for_http_and_check_with_default_port
FakeWeb.register_uri(:get, 'http://example.com/', :body => 'foo')
assert FakeWeb.registered_uri?(:get, 'http://example.com:80/')
end
def test_register_uri_with_no_port_for_https_and_check_with_default_port
FakeWeb.register_uri(:get, 'https://example.com/', :body => 'foo')
assert FakeWeb.registered_uri?(:get, 'https://example.com:443/')
end
def test_register_uri_with_no_port_for_https_and_check_with_443_on_http
FakeWeb.register_uri(:get, 'https://example.com/', :body => 'foo')
assert !FakeWeb.registered_uri?(:get, 'http://example.com:443/')
end
def test_register_uri_with_no_port_for_http_and_check_with_80_on_https
FakeWeb.register_uri(:get, 'http://example.com/', :body => 'foo')
assert !FakeWeb.registered_uri?(:get, 'https://example.com:80/')
end
def test_register_uri_for_any_method_explicitly
FakeWeb.register_uri(:any, "http://example.com/rpc_endpoint", :body => "OK")
assert FakeWeb.registered_uri?(:get, "http://example.com/rpc_endpoint")
assert FakeWeb.registered_uri?(:post, "http://example.com/rpc_endpoint")
assert FakeWeb.registered_uri?(:put, "http://example.com/rpc_endpoint")
assert FakeWeb.registered_uri?(:delete, "http://example.com/rpc_endpoint")
assert FakeWeb.registered_uri?(:any, "http://example.com/rpc_endpoint")
capture_stderr do # silence deprecation warning
assert FakeWeb.registered_uri?("http://example.com/rpc_endpoint")
end
end
def test_register_uri_for_get_method_only
FakeWeb.register_uri(:get, "http://example.com/users", :body => "User list")
assert FakeWeb.registered_uri?(:get, "http://example.com/users")
assert !FakeWeb.registered_uri?(:post, "http://example.com/users")
assert !FakeWeb.registered_uri?(:put, "http://example.com/users")
assert !FakeWeb.registered_uri?(:delete, "http://example.com/users")
assert !FakeWeb.registered_uri?(:any, "http://example.com/users")
capture_stderr do # silence deprecation warning
assert !FakeWeb.registered_uri?("http://example.com/users")
end
end
def test_clean_registry_affects_registered_uri
FakeWeb.register_uri(:get, "http://example.com", :body => "registered")
assert FakeWeb.registered_uri?(:get, "http://example.com")
FakeWeb.clean_registry
assert !FakeWeb.registered_uri?(:get, "http://example.com")
end
def test_clean_registry_affects_net_http_requests
FakeWeb.register_uri(:get, "http://example.com", :body => "registered")
response = Net::HTTP.start("example.com") { |query| query.get("/") }
assert_equal "registered", response.body
FakeWeb.clean_registry
assert_raise FakeWeb::NetConnectNotAllowedError do
Net::HTTP.start("example.com") { |query| query.get("/") }
end
end
def test_response_for_with_registered_uri
FakeWeb.register_uri(:get, 'http://mock/test_example.txt', :body => fixture_path("test_example.txt"))
assert_equal 'test example content', FakeWeb.response_for(:get, 'http://mock/test_example.txt').body
end
def test_response_for_with_unknown_uri
assert_nil FakeWeb.response_for(:get, 'http://example.com/')
end
def test_response_for_with_put_method
FakeWeb.register_uri(:put, "http://example.com", :body => "response")
assert_equal 'response', FakeWeb.response_for(:put, "http://example.com").body
end
def test_response_for_with_any_method_explicitly
FakeWeb.register_uri(:any, "http://example.com", :body => "response")
assert_equal 'response', FakeWeb.response_for(:get, "http://example.com").body
assert_equal 'response', FakeWeb.response_for(:any, "http://example.com").body
end
def test_content_for_registered_uri_with_port_and_request_with_port
FakeWeb.register_uri(:get, 'http://example.com:3000/', :body => 'test example content')
response = Net::HTTP.start('example.com', 3000) { |http| http.get('/') }
assert_equal 'test example content', response.body
end
def test_content_for_registered_uri_with_default_port_for_http_and_request_without_port
FakeWeb.register_uri(:get, 'http://example.com:80/', :body => 'test example content')
response = Net::HTTP.start('example.com') { |http| http.get('/') }
assert_equal 'test example content', response.body
end
def test_content_for_registered_uri_with_no_port_for_http_and_request_with_default_port
FakeWeb.register_uri(:get, 'http://example.com/', :body => 'test example content')
response = Net::HTTP.start('example.com', 80) { |http| http.get('/') }
assert_equal 'test example content', response.body
end
def test_content_for_registered_uri_with_default_port_for_https_and_request_with_default_port
FakeWeb.register_uri(:get, 'https://example.com:443/', :body => 'test example content')
http = Net::HTTP.new('example.com', 443)
http.use_ssl = true
response = http.get('/')
assert_equal 'test example content', response.body
end
def test_content_for_registered_uri_with_no_port_for_https_and_request_with_default_port
FakeWeb.register_uri(:get, 'https://example.com/', :body => 'test example content')
http = Net::HTTP.new('example.com', 443)
http.use_ssl = true
response = http.get('/')
assert_equal 'test example content', response.body
end
def test_content_for_registered_uris_with_ports_on_same_domain_and_request_without_port
FakeWeb.register_uri(:get, 'http://example.com:3000/', :body => 'port 3000')
FakeWeb.register_uri(:get, 'http://example.com/', :body => 'port 80')
response = Net::HTTP.start('example.com') { |http| http.get('/') }
assert_equal 'port 80', response.body
end
def test_content_for_registered_uris_with_ports_on_same_domain_and_request_with_port
FakeWeb.register_uri(:get, 'http://example.com:3000/', :body => 'port 3000')
FakeWeb.register_uri(:get, 'http://example.com/', :body => 'port 80')
response = Net::HTTP.start('example.com', 3000) { |http| http.get('/') }
assert_equal 'port 3000', response.body
end
def test_content_for_registered_uri_with_get_method_only
FakeWeb.allow_net_connect = false
FakeWeb.register_uri(:get, "http://example.com/", :body => "test example content")
http = Net::HTTP.new('example.com')
assert_equal 'test example content', http.get('/').body
assert_raises(FakeWeb::NetConnectNotAllowedError) { http.post('/', nil) }
assert_raises(FakeWeb::NetConnectNotAllowedError) { http.put('/', nil) }
assert_raises(FakeWeb::NetConnectNotAllowedError) { http.delete('/') }
end
def test_content_for_registered_uri_with_any_method_explicitly
FakeWeb.allow_net_connect = false
FakeWeb.register_uri(:any, "http://example.com/", :body => "test example content")
http = Net::HTTP.new('example.com')
assert_equal 'test example content', http.get('/').body
assert_equal 'test example content', http.post('/', nil).body
assert_equal 'test example content', http.put('/', nil).body
assert_equal 'test example content', http.delete('/').body
end
def test_content_for_registered_uri_with_any_method_implicitly
FakeWeb.allow_net_connect = false
capture_stderr do # silence deprecation warning
FakeWeb.register_uri("http://example.com/", :body => "test example content")
end
http = Net::HTTP.new('example.com')
assert_equal 'test example content', http.get('/').body
assert_equal 'test example content', http.post('/', nil).body
assert_equal 'test example content', http.put('/', nil).body
assert_equal 'test example content', http.delete('/').body
end
def test_mock_request_with_block
FakeWeb.register_uri(:get, 'http://mock/test_example.txt', :body => fixture_path("test_example.txt"))
response = Net::HTTP.start('mock') { |http| http.get('/test_example.txt') }
assert_equal 'test example content', response.body
end
def test_request_with_registered_body_yields_the_response_body_to_a_request_block
FakeWeb.register_uri(:get, "http://example.com", :body => "content")
body = nil
Net::HTTP.start("example.com") do |http|
http.get("/") do |response_body|
body = response_body
end
end
assert_equal "content", body
end
def test_request_with_registered_response_yields_the_response_body_to_a_request_block
fake_response = Net::HTTPOK.new('1.1', '200', 'OK')
fake_response.instance_variable_set(:@body, "content")
FakeWeb.register_uri(:get, 'http://example.com', :response => fake_response)
body = nil
Net::HTTP.start("example.com") do |http|
http.get("/") do |response_body|
body = response_body
end
end
assert_equal "content", body
end
def test_mock_request_with_undocumented_full_uri_argument_style
FakeWeb.register_uri(:get, 'http://mock/test_example.txt', :body => fixture_path("test_example.txt"))
response = Net::HTTP.start('mock') { |query| query.get('http://mock/test_example.txt') }
assert_equal 'test example content', response.body
end
def test_mock_request_with_undocumented_full_uri_argument_style_and_query
FakeWeb.register_uri(:get, 'http://mock/test_example.txt?a=b', :body => 'test query content')
response = Net::HTTP.start('mock') { |query| query.get('http://mock/test_example.txt?a=b') }
assert_equal 'test query content', response.body
end
def test_mock_post
FakeWeb.register_uri(:post, 'http://mock/test_example.txt', :body => fixture_path("test_example.txt"))
response = Net::HTTP.start('mock') { |query| query.post('/test_example.txt', '') }
assert_equal 'test example content', response.body
end
def test_mock_post_with_string_as_registered_uri
FakeWeb.register_uri(:post, 'http://mock/test_string.txt', :body => 'foo')
response = Net::HTTP.start('mock') { |query| query.post('/test_string.txt', '') }
assert_equal 'foo', response.body
end
def test_mock_post_with_body_sets_the_request_body
FakeWeb.register_uri(:post, "http://example.com/posts", :status => [201, "Created"])
http = Net::HTTP.new("example.com")
request = Net::HTTP::Post.new("/posts")
http.request(request, "title=Test")
assert_equal "title=Test", request.body
assert_equal 10, request.content_length
end
def test_mock_post_with_body_using_other_syntax_sets_the_request_body
FakeWeb.register_uri(:post, "http://example.com/posts", :status => [201, "Created"])
http = Net::HTTP.new("example.com")
request = Net::HTTP::Post.new("/posts")
request.body = "title=Test"
http.request(request)
assert_equal "title=Test", request.body
assert_equal 10, request.content_length
end
def test_real_post_with_body_sets_the_request_body
FakeWeb.allow_net_connect = true
setup_expectations_for_real_apple_hot_news_request :method => "POST",
:path => "/posts", :request_body => "title=Test"
http = Net::HTTP.new("images.apple.com")
request = Net::HTTP::Post.new("/posts")
request["Content-Type"] = "application/x-www-form-urlencoded"
http.request(request, "title=Test")
assert_equal "title=Test", request.body
assert_equal 10, request.content_length
end
def test_mock_get_with_request_as_registered_uri
fake_response = Net::HTTPOK.new('1.1', '200', 'OK')
FakeWeb.register_uri(:get, 'http://mock/test_response', :response => fake_response)
response = Net::HTTP.start('mock') { |query| query.get('/test_response') }
assert_equal fake_response, response
end
def test_mock_get_with_request_from_file_as_registered_uri
FakeWeb.register_uri(:get, 'http://www.google.com/', :response => fixture_path("google_response_without_transfer_encoding"))
response = Net::HTTP.start('www.google.com') { |query| query.get('/') }
assert_equal '200', response.code
assert response.body.include?('Google')
end
def test_mock_post_with_request_from_file_as_registered_uri
FakeWeb.register_uri(:post, 'http://www.google.com/', :response => fixture_path("google_response_without_transfer_encoding"))
response = Net::HTTP.start('www.google.com') { |query| query.post('/', '') }
assert_equal "200", response.code
assert response.body.include?('Google')
end
def test_proxy_request
FakeWeb.register_uri(:get, 'http://www.example.com/', :body => "hello world")
FakeWeb.register_uri(:get, 'http://your.proxy.host/', :body => "lala")
response = nil
Net::HTTP::Proxy('your.proxy.host', 8080).start('www.example.com') do |http|
response = http.get('/')
end
assert_equal "hello world", response.body
end
def test_https_request
FakeWeb.register_uri(:get, 'https://www.example.com/', :body => "Hello World")
http = Net::HTTP.new('www.example.com', 443)
http.use_ssl = true
response = http.get('/')
assert_equal "Hello World", response.body
end
def test_register_unimplemented_response
FakeWeb.register_uri(:get, 'http://mock/unimplemented', :response => 1)
exception = assert_raises ArgumentError do
Net::HTTP.start('mock') { |q| q.get('/unimplemented') }
end
assert_match "Handler not implemented", exception.message
end
def test_specifying_nil_for_body_triggers_net_http_behavior_of_nil_body
FakeWeb.register_uri(:head, "http://example.com", :body => nil)
response = Net::HTTP.start("example.com") { |query| query.head("/") }
assert_nil response.body
end
def test_specifying_empty_string_for_body_triggers_net_http_behavior_of_nil_body
FakeWeb.register_uri(:head, "http://example.com", :body => '')
response = Net::HTTP.start("example.com") { |query| query.head("/") }
assert_nil response.body
end
def test_real_http_request
FakeWeb.allow_net_connect = true
setup_expectations_for_real_apple_hot_news_request
resp = nil
Net::HTTP.start('images.apple.com') do |query|
resp = query.get('/main/rss/hotnews/hotnews.rss')
end
assert resp.body.include?('Apple')
assert resp.body.include?('News')
end
def test_real_http_request_with_undocumented_full_uri_argument_style
FakeWeb.allow_net_connect = true
setup_expectations_for_real_apple_hot_news_request(:path => 'http://images.apple.com/main/rss/hotnews/hotnews.rss')
resp = nil
Net::HTTP.start('images.apple.com') do |query|
resp = query.get('http://images.apple.com/main/rss/hotnews/hotnews.rss')
end
assert resp.body.include?('Apple')
assert resp.body.include?('News')
end
def test_real_https_request
FakeWeb.allow_net_connect = true
setup_expectations_for_real_apple_hot_news_request(:port => 443)
http = Net::HTTP.new('images.apple.com', 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # silence certificate warning
response = http.get('/main/rss/hotnews/hotnews.rss')
assert response.body.include?('Apple')
assert response.body.include?('News')
end
def test_real_request_on_same_domain_as_mock
FakeWeb.allow_net_connect = true
setup_expectations_for_real_apple_hot_news_request
FakeWeb.register_uri(:get, 'http://images.apple.com/test_string.txt', :body => 'foo')
resp = nil
Net::HTTP.start('images.apple.com') do |query|
resp = query.get('/main/rss/hotnews/hotnews.rss')
end
assert resp.body.include?('Apple')
assert resp.body.include?('News')
end
def test_mock_request_on_real_domain
FakeWeb.register_uri(:get, 'http://images.apple.com/test_string.txt', :body => 'foo')
resp = nil
Net::HTTP.start('images.apple.com') do |query|
resp = query.get('/test_string.txt')
end
assert_equal 'foo', resp.body
end
def test_mock_post_that_raises_exception
FakeWeb.register_uri(:post, 'http://mock/raising_exception.txt', :exception => StandardError)
assert_raises(StandardError) do
Net::HTTP.start('mock') do |query|
query.post('/raising_exception.txt', 'some data')
end
end
end
def test_mock_post_that_raises_an_http_error
FakeWeb.register_uri(:post, 'http://mock/raising_exception.txt', :exception => Net::HTTPError)
assert_raises(Net::HTTPError) do
Net::HTTP.start('mock') do |query|
query.post('/raising_exception.txt', '')
end
end
end
def test_raising_an_exception_that_requires_an_argument_to_instantiate
FakeWeb.register_uri(:get, "http://example.com/timeout.txt", :exception => Timeout::Error)
assert_raises(Timeout::Error) do
Net::HTTP.get(URI.parse("http://example.com/timeout.txt"))
end
end
def test_mock_instance_syntax
FakeWeb.register_uri(:get, 'http://mock/test_example.txt', :body => fixture_path("test_example.txt"))
response = nil
uri = URI.parse('http://mock/test_example.txt')
http = Net::HTTP.new(uri.host, uri.port)
response = http.start do
http.get(uri.path)
end
assert_equal 'test example content', response.body
end
def test_mock_via_nil_proxy
response = nil
proxy_address = nil
proxy_port = nil
FakeWeb.register_uri(:get, 'http://mock/test_example.txt', :body => fixture_path("test_example.txt"))
uri = URI.parse('http://mock/test_example.txt')
http = Net::HTTP::Proxy(proxy_address, proxy_port).new(
uri.host, (uri.port or 80))
response = http.start do
http.get(uri.path)
end
assert_equal 'test example content', response.body
end
def test_response_type
FakeWeb.register_uri(:get, 'http://mock/test_example.txt', :body => "test")
response = Net::HTTP.start('mock') { |http| http.get('/test_example.txt') }
assert_kind_of Net::HTTPSuccess, response
end
def test_mock_request_that_raises_an_http_error_with_a_specific_status
FakeWeb.register_uri(:get, 'http://mock/raising_exception.txt', :exception => Net::HTTPError, :status => ['404', 'Not Found'])
exception = assert_raises(Net::HTTPError) do
Net::HTTP.start('mock') { |http| http.get('/raising_exception.txt') }
end
assert_equal '404', exception.response.code
assert_equal 'Not Found', exception.response.msg
end
def test_mock_rotate_responses
FakeWeb.register_uri(:get, 'http://mock/multiple_test_example.txt',
[ {:body => fixture_path("test_example.txt"), :times => 2},
{:body => "thrice", :times => 3},
{:body => "ever_more"} ])
uri = URI.parse('http://mock/multiple_test_example.txt')
2.times { assert_equal 'test example content', Net::HTTP.get(uri) }
3.times { assert_equal 'thrice', Net::HTTP.get(uri) }
4.times { assert_equal 'ever_more', Net::HTTP.get(uri) }
end
def test_mock_request_using_response_with_transfer_encoding_header_has_valid_transfer_encoding_header
FakeWeb.register_uri(:get, 'http://www.google.com/', :response => fixture_path("google_response_with_transfer_encoding"))
response = Net::HTTP.start('www.google.com') { |query| query.get('/') }
assert_not_nil response['transfer-encoding']
assert response['transfer-encoding'] == 'chunked'
end
def test_mock_request_using_response_without_transfer_encoding_header_does_not_have_a_transfer_encoding_header
FakeWeb.register_uri(:get, 'http://www.google.com/', :response => fixture_path("google_response_without_transfer_encoding"))
response = nil
response = Net::HTTP.start('www.google.com') { |query| query.get('/') }
assert !response.key?('transfer-encoding')
end
def test_mock_request_using_response_from_curl_has_original_transfer_encoding_header
FakeWeb.register_uri(:get, 'http://www.google.com/', :response => fixture_path("google_response_from_curl"))
response = Net::HTTP.start('www.google.com') { |query| query.get('/') }
assert_not_nil response['transfer-encoding']
assert response['transfer-encoding'] == 'chunked'
end
def test_txt_file_should_have_three_lines
FakeWeb.register_uri(:get, 'http://www.google.com/', :body => fixture_path("test_txt_file"))
response = Net::HTTP.start('www.google.com') { |query| query.get('/') }
assert response.body.split(/\n/).size == 3, "response has #{response.body.split(/\n/).size} lines should have 3"
end
def test_requiring_fakeweb_instead_of_fake_web
require "fakeweb"
end
def test_registering_with_string_containing_null_byte
# Regression test for File.exists? raising an ArgumentError ("string
# contains null byte") since :response first tries to find by filename.
# The string should be treated as a response body, instead, and an
# EOFError is raised when the byte is encountered.
FakeWeb.register_uri(:get, "http://example.com", :response => "test\0test")
assert_raise EOFError do
Net::HTTP.get(URI.parse("http://example.com"))
end
FakeWeb.register_uri(:get, "http://example.com", :body => "test\0test")
body = Net::HTTP.get(URI.parse("http://example.com"))
assert_equal "test\0test", body
end
def test_registering_with_string_that_is_a_directory_name
# Similar to above, but for Errno::EISDIR being raised since File.exists?
# returns true for directories
FakeWeb.register_uri(:get, "http://example.com", :response => File.dirname(__FILE__))
assert_raise EOFError do
Net::HTTP.get(URI.parse("http://example.com"))
end
FakeWeb.register_uri(:get, "http://example.com", :body => File.dirname(__FILE__))
body = Net::HTTP.get(URI.parse("http://example.com"))
assert_equal File.dirname(__FILE__), body
end
def test_registering_with_a_body_pointing_to_a_pathname
path = Pathname.new(fixture_path("test_example.txt"))
FakeWeb.register_uri(:get, "http://example.com", :body => path)
response = Net::HTTP.start("example.com") { |http| http.get("/") }
assert_equal "test example content", response.body
end
def test_registering_with_a_body_pointing_to_a_pathname_does_not_modify_options
path = Pathname.new(fixture_path("test_example.txt"))
options = {:body => path}
options_before_request = options.dup
FakeWeb.register_uri(:get, "http://example.com", options)
Net::HTTP.start("example.com") { |http| http.get("/") }
assert_equal options_before_request, options
end
def test_registering_with_a_response_pointing_to_a_pathname
path = Pathname.new(fixture_path("google_response_without_transfer_encoding"))
FakeWeb.register_uri(:get, "http://google.com", :response => path)
response = Net::HTTP.start("google.com") { |http| http.get("/") }
assert response.body.include?("Google")
end
def test_registering_with_a_response_pointing_to_a_pathname_does_not_modify_options
path = Pathname.new(fixture_path("google_response_without_transfer_encoding"))
options = {:response => path}
options_before_request = options.dup
FakeWeb.register_uri(:get, "http://google.com", options)
Net::HTTP.start("google.com") { |http| http.get("/") }
assert_equal options_before_request, options
end
def test_http_version_from_string_response
FakeWeb.register_uri(:get, "http://example.com", :body => "example")
response = Net::HTTP.start("example.com") { |http| http.get("/") }
assert_equal "1.0", response.http_version
end
def test_http_version_from_file_response
FakeWeb.register_uri(:get, "http://example.com", :body => fixture_path("test_example.txt"))
response = Net::HTTP.start("example.com") { |http| http.get("/") }
assert_equal "1.0", response.http_version
end
def test_version
assert_equal "1.3.0", FakeWeb::VERSION
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_fake_authentication.rb 0000644 0001750 0001750 00000007260 13141466106 025401 0 ustar boutil boutil require 'test_helper'
class TestFakeAuthentication < Test::Unit::TestCase
def test_register_uri_with_authentication
FakeWeb.register_uri(:get, 'http://user:pass@mock/test_example.txt', :body => "example")
assert FakeWeb.registered_uri?(:get, 'http://user:pass@mock/test_example.txt')
end
def test_register_uri_with_authentication_doesnt_trigger_without
FakeWeb.register_uri(:get, 'http://user:pass@mock/test_example.txt', :body => "example")
assert !FakeWeb.registered_uri?(:get, 'http://mock/test_example.txt')
end
def test_register_uri_with_authentication_doesnt_trigger_with_incorrect_credentials
FakeWeb.register_uri(:get, 'http://user:pass@mock/test_example.txt', :body => "example")
assert !FakeWeb.registered_uri?(:get, 'http://user:wrong@mock/test_example.txt')
end
def test_unauthenticated_request
FakeWeb.register_uri(:get, 'http://mock/auth.txt', :body => 'unauthorized')
http = Net::HTTP.new('mock', 80)
req = Net::HTTP::Get.new('/auth.txt')
assert_equal 'unauthorized', http.request(req).body
end
def test_authenticated_request
FakeWeb.register_uri(:get, 'http://user:pass@mock/auth.txt', :body => 'authorized')
http = Net::HTTP.new('mock',80)
req = Net::HTTP::Get.new('/auth.txt')
req.basic_auth 'user', 'pass'
assert_equal 'authorized', http.request(req).body
end
def test_authenticated_request_where_only_userinfo_differs
FakeWeb.register_uri(:get, 'http://user:pass@mock/auth.txt', :body => 'first user')
FakeWeb.register_uri(:get, 'http://user2:pass@mock/auth.txt', :body => 'second user')
http = Net::HTTP.new('mock')
req = Net::HTTP::Get.new('/auth.txt')
req.basic_auth 'user2', 'pass'
assert_equal 'second user', http.request(req).body
end
def test_basic_auth_support_is_transparent_to_oauth
FakeWeb.register_uri(:get, "http://sp.example.com/protected", :body => "secret")
# from http://oauth.net/core/1.0/#auth_header
auth_header = <<-HEADER
OAuth realm="http://sp.example.com/",
oauth_consumer_key="0685bd9184jfhq22",
oauth_token="ad180jjd733klru7",
oauth_signature_method="HMAC-SHA1",
oauth_signature="wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D",
oauth_timestamp="137131200",
oauth_nonce="4572616e48616d6d65724c61686176",
oauth_version="1.0"
HEADER
auth_header.gsub!(/\s+/, " ").strip!
http = Net::HTTP.new("sp.example.com", 80)
response = nil
http.start do |request|
response = request.get("/protected", {"authorization" => auth_header})
end
assert_equal "secret", response.body
end
def test_basic_auth_when_userinfo_contains_allowed_unencoded_characters
FakeWeb.register_uri(:get, "http://roses&hel1o,(+$):so;longs=@example.com", :body => "authorized")
http = Net::HTTP.new("example.com")
request = Net::HTTP::Get.new("/")
request.basic_auth("roses&hel1o,(+$)", "so;longs=")
assert_equal "authorized", http.request(request).body
end
def test_basic_auth_when_userinfo_contains_encoded_at_sign
FakeWeb.register_uri(:get, "http://user%40example.com:secret@example.com", :body => "authorized")
http = Net::HTTP.new("example.com")
request = Net::HTTP::Get.new("/")
request.basic_auth("user@example.com", "secret")
assert_equal "authorized", http.request(request).body
end
def test_basic_auth_when_userinfo_contains_allowed_encoded_characters
FakeWeb.register_uri(:get, "http://us%20er:sec%20%2F%2Fret%3F@example.com", :body => "authorized")
http = Net::HTTP.new("example.com")
request = Net::HTTP::Get.new("/")
request.basic_auth("us er", "sec //ret?")
assert_equal "authorized", http.request(request).body
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/fixtures/ 0000755 0001750 0001750 00000000000 13252215206 021650 5 ustar boutil boutil ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/fixtures/test_example.txt 0000644 0001750 0001750 00000000024 13141466106 025103 0 ustar boutil boutil test example content ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/fixtures/test_txt_file 0000644 0001750 0001750 00000000024 13141466106 024450 0 ustar boutil boutil line 1
line 2
line 3 ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_allow_net_connect.rb 0000644 0001750 0001750 00000015217 13141466106 025072 0 ustar boutil boutil require 'test_helper'
class TestFakeWebAllowNetConnect < Test::Unit::TestCase
def test_unregistered_requests_are_passed_through_when_allow_net_connect_is_true
FakeWeb.allow_net_connect = true
setup_expectations_for_real_apple_hot_news_request
Net::HTTP.get(URI.parse("http://images.apple.com/main/rss/hotnews/hotnews.rss"))
end
def test_raises_for_unregistered_requests_when_allow_net_connect_is_false
FakeWeb.allow_net_connect = false
assert_raise FakeWeb::NetConnectNotAllowedError do
Net::HTTP.get(URI.parse("http://example.com/"))
end
end
def test_unregistered_requests_are_passed_through_when_allow_net_connect_is_the_same_string
FakeWeb.allow_net_connect = "http://images.apple.com/main/rss/hotnews/hotnews.rss"
setup_expectations_for_real_apple_hot_news_request
Net::HTTP.get(URI.parse("http://images.apple.com/main/rss/hotnews/hotnews.rss"))
end
def test_unregistered_requests_are_passed_through_when_allow_net_connect_is_the_same_string_with_default_port
FakeWeb.allow_net_connect = "http://images.apple.com:80/main/rss/hotnews/hotnews.rss"
setup_expectations_for_real_apple_hot_news_request
Net::HTTP.get(URI.parse("http://images.apple.com/main/rss/hotnews/hotnews.rss"))
end
def test_unregistered_requests_are_passed_through_when_allow_net_connect_is_the_same_uri
FakeWeb.allow_net_connect = URI.parse("http://images.apple.com/main/rss/hotnews/hotnews.rss")
setup_expectations_for_real_apple_hot_news_request
Net::HTTP.get(URI.parse("http://images.apple.com/main/rss/hotnews/hotnews.rss"))
end
def test_unregistered_requests_are_passed_through_when_allow_net_connect_is_a_matching_regexp
FakeWeb.allow_net_connect = %r[^http://images\.apple\.com]
setup_expectations_for_real_apple_hot_news_request
Net::HTTP.get(URI.parse("http://images.apple.com/main/rss/hotnews/hotnews.rss"))
end
def test_raises_for_unregistered_requests_when_allow_net_connect_is_a_different_string
FakeWeb.allow_net_connect = "http://example.com"
assert_raise FakeWeb::NetConnectNotAllowedError do
Net::HTTP.get(URI.parse("http://example.com/path"))
end
end
def test_raises_for_unregistered_requests_when_allow_net_connect_is_a_different_uri
FakeWeb.allow_net_connect = URI.parse("http://example.com")
assert_raise FakeWeb::NetConnectNotAllowedError do
Net::HTTP.get(URI.parse("http://example.com/path"))
end
end
def test_raises_for_unregistered_requests_when_allow_net_connect_is_a_non_matching_regexp
FakeWeb.allow_net_connect = %r[example\.net]
assert_raise FakeWeb::NetConnectNotAllowedError do
Net::HTTP.get(URI.parse("http://example.com"))
end
end
def test_changing_allow_net_connect_from_string_to_false_corretly_removes_whitelist
FakeWeb.allow_net_connect = "http://example.com"
FakeWeb.allow_net_connect = false
assert_raise FakeWeb::NetConnectNotAllowedError do
Net::HTTP.get(URI.parse("http://example.com"))
end
end
def test_changing_allow_net_connect_from_true_to_string_corretly_limits_connections
FakeWeb.allow_net_connect = true
FakeWeb.allow_net_connect = "http://example.com"
assert_raise FakeWeb::NetConnectNotAllowedError do
Net::HTTP.get(URI.parse("http://example.net"))
end
end
def test_exception_message_includes_unregistered_request_method_and_uri_but_no_default_port
FakeWeb.allow_net_connect = false
exception = assert_raise FakeWeb::NetConnectNotAllowedError do
Net::HTTP.get(URI.parse("http://example.com/"))
end
assert exception.message.include?("GET http://example.com/")
exception = assert_raise FakeWeb::NetConnectNotAllowedError do
http = Net::HTTP.new("example.com", 443)
http.use_ssl = true
http.get("/")
end
assert exception.message.include?("GET https://example.com/")
end
def test_exception_message_includes_unregistered_request_port_when_not_default
FakeWeb.allow_net_connect = false
exception = assert_raise FakeWeb::NetConnectNotAllowedError do
Net::HTTP.start("example.com", 8000) { |http| http.get("/") }
end
assert exception.message.include?("GET http://example.com:8000/")
exception = assert_raise FakeWeb::NetConnectNotAllowedError do
http = Net::HTTP.new("example.com", 4433)
http.use_ssl = true
http.get("/")
end
assert exception.message.include?("GET https://example.com:4433/")
end
def test_exception_message_includes_unregistered_request_port_when_not_default_with_path
FakeWeb.allow_net_connect = false
exception = assert_raise FakeWeb::NetConnectNotAllowedError do
Net::HTTP.start("example.com", 8000) { |http| http.get("/test") }
end
assert exception.message.include?("GET http://example.com:8000/test")
exception = assert_raise FakeWeb::NetConnectNotAllowedError do
http = Net::HTTP.new("example.com", 4433)
http.use_ssl = true
http.get("/test")
end
assert exception.message.include?("GET https://example.com:4433/test")
end
def test_question_mark_method_returns_true_after_setting_allow_net_connect_to_true
FakeWeb.allow_net_connect = true
assert FakeWeb.allow_net_connect?
end
def test_question_mark_method_returns_false_after_setting_allow_net_connect_to_false
FakeWeb.allow_net_connect = false
assert !FakeWeb.allow_net_connect?
end
def test_question_mark_method_raises_with_no_argument_when_allow_net_connect_is_a_whitelist
FakeWeb.allow_net_connect = "http://example.com"
exception = assert_raise ArgumentError do
FakeWeb.allow_net_connect?
end
assert_equal "You must supply a URI to test", exception.message
end
def test_question_mark_method_returns_true_when_argument_is_same_uri_as_allow_net_connect_string
FakeWeb.allow_net_connect = "http://example.com"
assert FakeWeb.allow_net_connect?("http://example.com/")
end
def test_question_mark_method_returns_true_when_argument_matches_allow_net_connect_regexp
FakeWeb.allow_net_connect = %r[^https?://example.com/]
assert FakeWeb.allow_net_connect?("http://example.com/path")
assert FakeWeb.allow_net_connect?("https://example.com:443/")
end
def test_question_mark_method_returns_false_when_argument_does_not_match_allow_net_connect_regexp
FakeWeb.allow_net_connect = %r[^http://example.com/]
assert !FakeWeb.allow_net_connect?("http://example.com:8080")
end
end
class TestFakeWebAllowNetConnectWithCleanState < Test::Unit::TestCase
# Our test_helper.rb sets allow_net_connect = false in an inherited #setup
# method. Disable that here to test the default setting.
def setup; end
def teardown; end
def test_allow_net_connect_is_true_by_default
assert FakeWeb.allow_net_connect?
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_response_headers.rb 0000644 0001750 0001750 00000007742 13141466106 024732 0 ustar boutil boutil require 'test_helper'
class TestResponseHeaders < Test::Unit::TestCase
def test_content_type_when_registering_with_string_and_content_type_header_as_symbol_option
FakeWeb.register_uri(:get, "http://example.com/users.json", :body => '[{"username": "chrisk"}]', :content_type => "application/json")
response = Net::HTTP.start("example.com") { |query| query.get("/users.json") }
assert_equal '[{"username": "chrisk"}]', response.body
assert_equal "application/json", response['Content-Type']
end
def test_content_type_when_registering_with_string_and_content_type_header_as_string_option
FakeWeb.register_uri(:get, "http://example.com/users.json", :body => '[{"username": "chrisk"}]', 'Content-Type' => "application/json")
response = Net::HTTP.start("example.com") { |query| query.get("/users.json") }
assert_equal "application/json", response['Content-Type']
end
def test_content_type_when_registering_with_string_only
FakeWeb.register_uri(:get, "http://example.com/users.json", :body => '[{"username": "chrisk"}]')
response = Net::HTTP.start("example.com") { |query| query.get("/users.json") }
assert_equal '[{"username": "chrisk"}]', response.body
assert_nil response['Content-Type']
end
def test_cookies_when_registering_with_file_and_set_cookie_header
FakeWeb.register_uri(:get, "http://example.com/", :body => fixture_path("test_example.txt"),
:set_cookie => "user_id=1; example=yes")
response = Net::HTTP.start("example.com") { |query| query.get("/") }
assert_equal "test example content", response.body
assert_equal "user_id=1; example=yes", response['Set-Cookie']
end
def test_multiple_set_cookie_headers
FakeWeb.register_uri(:get, "http://example.com", :set_cookie => ["user_id=1", "example=yes"])
response = Net::HTTP.start("example.com") { |query| query.get("/") }
assert_equal ["user_id=1", "example=yes"], response.get_fields('Set-Cookie')
assert_equal "user_id=1, example=yes", response['Set-Cookie']
end
def test_registering_with_baked_response_ignores_header_options
fake_response = Net::HTTPOK.new('1.1', '200', 'OK')
fake_response["Server"] = "Apache/1.3.27 (Unix)"
FakeWeb.register_uri(:get, "http://example.com/", :response => fake_response,
:server => "FakeWeb/1.2.3 (Ruby)")
response = Net::HTTP.start("example.com") { |query| query.get("/") }
assert_equal "200", response.code
assert_equal "OK", response.message
assert_equal "Apache/1.3.27 (Unix)", response["Server"]
end
def test_headers_are_rotated_when_registering_with_response_rotation
FakeWeb.register_uri(:get, "http://example.com",
[{:body => 'test1', :expires => "Thu, 14 Jun 2009 16:00:00 GMT",
:content_type => "text/plain"},
{:body => 'test2', :expires => "Thu, 14 Jun 2009 16:00:01 GMT"}])
first_response = second_response = nil
Net::HTTP.start("example.com") do |query|
first_response = query.get("/")
second_response = query.get("/")
end
assert_equal 'test1', first_response.body
assert_equal "Thu, 14 Jun 2009 16:00:00 GMT", first_response['Expires']
assert_equal "text/plain", first_response['Content-Type']
assert_equal 'test2', second_response.body
assert_equal "Thu, 14 Jun 2009 16:00:01 GMT", second_response['Expires']
assert_nil second_response['Content-Type']
end
def test_registering_with_status_option_and_response_headers
FakeWeb.register_uri(:get, "http://example.com", :status => ["301", "Moved Permanently"],
:location => "http://www.example.com")
response = Net::HTTP.start("example.com") { |query| query.get("/") }
assert_equal "301", response.code
assert_equal "Moved Permanently", response.message
assert_equal "http://www.example.com", response["Location"]
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_fake_web_open_uri.rb 0000644 0001750 0001750 00000004274 13141466106 025041 0 ustar boutil boutil require 'test_helper'
class TestFakeWebOpenURI < Test::Unit::TestCase
def test_content_for_registered_uri
FakeWeb.register_uri(:get, 'http://mock/test_example.txt', :body => fixture_path("test_example.txt"))
assert_equal 'test example content', FakeWeb.response_for(:get, 'http://mock/test_example.txt').body
end
def test_mock_open
FakeWeb.register_uri(:get, 'http://mock/test_example.txt', :body => fixture_path("test_example.txt"))
assert_equal 'test example content', open('http://mock/test_example.txt').read
end
def test_mock_open_with_string_as_registered_uri
FakeWeb.register_uri(:get, 'http://mock/test_string.txt', :body => 'foo')
assert_equal 'foo', open('http://mock/test_string.txt').string
end
def test_real_open
FakeWeb.allow_net_connect = true
setup_expectations_for_real_apple_hot_news_request
resp = open('http://images.apple.com/main/rss/hotnews/hotnews.rss')
assert_equal "200", resp.status.first
body = resp.read
assert body.include?('Apple')
assert body.include?('News')
end
def test_mock_open_that_raises_exception
FakeWeb.register_uri(:get, 'http://mock/raising_exception.txt', :exception => StandardError)
assert_raises(StandardError) do
open('http://mock/raising_exception.txt')
end
end
def test_mock_open_that_raises_an_http_error
FakeWeb.register_uri(:get, 'http://mock/raising_exception.txt', :exception => OpenURI::HTTPError)
assert_raises(OpenURI::HTTPError) do
open('http://mock/raising_exception.txt')
end
end
def test_mock_open_that_raises_an_http_error_with_a_specific_status
FakeWeb.register_uri(:get, 'http://mock/raising_exception.txt', :exception => OpenURI::HTTPError, :status => ['123', 'jodel'])
exception = assert_raises(OpenURI::HTTPError) do
open('http://mock/raising_exception.txt')
end
assert_equal '123', exception.io.code
assert_equal 'jodel', exception.io.message
end
def test_mock_open_with_block
FakeWeb.register_uri(:get, 'http://mock/test_example.txt', :body => fixture_path("test_example.txt"))
body = open('http://mock/test_example.txt') { |f| f.readlines }
assert_equal 'test example content', body.first
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_missing_open_uri.rb 0000644 0001750 0001750 00000001107 13141466106 024737 0 ustar boutil boutil require 'test_helper'
class TestMissingOpenURI < Test::Unit::TestCase
def setup
super
@saved_open_uri = OpenURI
Object.send(:remove_const, :OpenURI)
end
def teardown
super
Object.const_set(:OpenURI, @saved_open_uri)
end
def test_register_using_exception_without_open_uri
# regression test for Responder needing OpenURI::HTTPError to be defined
FakeWeb.register_uri(:get, "http://example.com/", :exception => StandardError)
assert_raises(StandardError) do
Net::HTTP.start("example.com") { |http| http.get("/") }
end
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_utility.rb 0000644 0001750 0001750 00000006506 13141466106 023101 0 ustar boutil boutil require 'test_helper'
class TestUtility < Test::Unit::TestCase
def test_decode_userinfo_from_header_handles_basic_auth
authorization_header = "Basic dXNlcm5hbWU6c2VjcmV0"
userinfo = FakeWeb::Utility.decode_userinfo_from_header(authorization_header)
assert_equal "username:secret", userinfo
end
def test_encode_unsafe_chars_in_userinfo_does_not_encode_userinfo_safe_punctuation
userinfo = "user;&=+$,:secret"
assert_equal userinfo, FakeWeb::Utility.encode_unsafe_chars_in_userinfo(userinfo)
end
def test_encode_unsafe_chars_in_userinfo_does_not_encode_rfc_3986_unreserved_characters
userinfo = "-_.!~*'()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:secret"
assert_equal userinfo, FakeWeb::Utility.encode_unsafe_chars_in_userinfo(userinfo)
end
def test_encode_unsafe_chars_in_userinfo_does_encode_other_characters
userinfo, safe_userinfo = 'us#rn@me:sec//ret?"', 'us%23rn%40me:sec%2F%2Fret%3F%22'
assert_equal safe_userinfo, FakeWeb::Utility.encode_unsafe_chars_in_userinfo(userinfo)
end
def test_strip_default_port_from_uri_strips_80_from_http_with_path
uri = "http://example.com:80/foo/bar"
stripped_uri = FakeWeb::Utility.strip_default_port_from_uri(uri)
assert_equal "http://example.com/foo/bar", stripped_uri
end
def test_strip_default_port_from_uri_strips_80_from_http_without_path
uri = "http://example.com:80"
stripped_uri = FakeWeb::Utility.strip_default_port_from_uri(uri)
assert_equal "http://example.com", stripped_uri
end
def test_strip_default_port_from_uri_strips_443_from_https_without_path
uri = "https://example.com:443"
stripped_uri = FakeWeb::Utility.strip_default_port_from_uri(uri)
assert_equal "https://example.com", stripped_uri
end
def test_strip_default_port_from_uri_strips_443_from_https
uri = "https://example.com:443/foo/bar"
stripped_uri = FakeWeb::Utility.strip_default_port_from_uri(uri)
assert_equal "https://example.com/foo/bar", stripped_uri
end
def test_strip_default_port_from_uri_does_not_strip_8080_from_http
uri = "http://example.com:8080/foo/bar"
assert_equal uri, FakeWeb::Utility.strip_default_port_from_uri(uri)
end
def test_strip_default_port_from_uri_does_not_strip_443_from_http
uri = "http://example.com:443/foo/bar"
assert_equal uri, FakeWeb::Utility.strip_default_port_from_uri(uri)
end
def test_strip_default_port_from_uri_does_not_strip_80_from_query_string
uri = "http://example.com/?a=:80&b=c"
assert_equal uri, FakeWeb::Utility.strip_default_port_from_uri(uri)
end
def test_strip_default_port_from_uri_does_not_modify_strings_that_do_not_start_with_http_or_https
uri = "httpz://example.com:80/"
assert_equal uri, FakeWeb::Utility.strip_default_port_from_uri(uri)
end
def test_request_uri_as_string
http = Net::HTTP.new("www.example.com", 80)
request = Net::HTTP::Get.new("/index.html")
expected = "http://www.example.com:80/index.html"
assert_equal expected, FakeWeb::Utility.request_uri_as_string(http, request)
end
def test_uri_escape_delegates_to_uri_parser_when_available
parsing_object = URI.const_defined?(:Parser) ? URI::Parser.any_instance : URI
parsing_object.expects(:escape).with("string", /unsafe/).returns("escaped")
assert_equal "escaped", FakeWeb::Utility.uri_escape("string", /unsafe/)
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_regexes.rb 0000644 0001750 0001750 00000020304 13141466106 023030 0 ustar boutil boutil require 'test_helper'
class TestRegexes < Test::Unit::TestCase
def test_registered_uri_with_pattern
FakeWeb.register_uri(:get, %r|http://example.com/test_example/\d+|, :body => "example")
assert FakeWeb.registered_uri?(:get, "http://example.com/test_example/25")
assert !FakeWeb.registered_uri?(:get, "http://example.com/test_example/abc")
end
def test_response_for_with_matching_registered_uri
FakeWeb.register_uri(:get, %r|http://www.google.com|, :body => "Welcome to Google!")
assert_equal "Welcome to Google!", FakeWeb.response_for(:get, "http://www.google.com").body
end
def test_response_for_with_matching_registered_uri_and_get_method_matching_to_any_method
FakeWeb.register_uri(:any, %r|http://www.example.com|, :body => "example")
assert_equal "example", FakeWeb.response_for(:get, "http://www.example.com").body
end
def test_registered_uri_with_authentication_and_pattern
FakeWeb.register_uri(:get, %r|http://user:pass@mock/example\.\w+|i, :body => "example")
assert FakeWeb.registered_uri?(:get, 'http://user:pass@mock/example.txt')
end
def test_registered_uri_with_authentication_and_pattern_handles_case_insensitivity
FakeWeb.register_uri(:get, %r|http://user:pass@mock/example\.\w+|i, :body => "example")
assert FakeWeb.registered_uri?(:get, 'http://uSeR:PAss@mock/example.txt')
end
def test_request_with_authentication_and_pattern_handles_case_insensitivity
FakeWeb.register_uri(:get, %r|http://user:pass@mock/example\.\w+|i, :body => "example")
http = Net::HTTP.new('mock', 80)
req = Net::HTTP::Get.new('/example.txt')
req.basic_auth 'uSeR', 'PAss'
assert_equal "example", http.request(req).body
end
def test_requesting_a_uri_that_matches_two_registered_regexes_raises_an_error
FakeWeb.register_uri(:get, %r|http://example\.com/|, :body => "first")
FakeWeb.register_uri(:get, %r|http://example\.com/a|, :body => "second")
assert_raise FakeWeb::MultipleMatchingURIsError do
Net::HTTP.start("example.com") { |query| query.get('/a') }
end
end
def test_requesting_a_uri_that_matches_two_registered_regexes_raises_an_error_including_request_info
FakeWeb.register_uri(:get, %r|http://example\.com/|, :body => "first")
FakeWeb.register_uri(:get, %r|http://example\.com/a|, :body => "second")
begin
Net::HTTP.start("example.com") { |query| query.get('/a') }
rescue FakeWeb::MultipleMatchingURIsError => exception
end
assert exception.message.include?("GET http://example.com/a")
end
def test_registry_does_not_find_using_mismatched_protocols_or_ports_when_registered_with_both
FakeWeb.register_uri(:get, %r|http://www.example.com:80|, :body => "example")
assert !FakeWeb.registered_uri?(:get, "https://www.example.com:80")
assert !FakeWeb.registered_uri?(:get, "http://www.example.com:443")
end
def test_registry_finds_using_non_default_port
FakeWeb.register_uri(:get, %r|example\.com:8080|, :body => "example")
assert FakeWeb.registered_uri?(:get, "http://www.example.com:8080/path")
assert FakeWeb.registered_uri?(:get, "https://www.example.com:8080/path")
end
def test_registry_finds_using_default_port_and_http_when_registered_with_explicit_port_80
FakeWeb.register_uri(:get, %r|example\.com:80|, :body => "example")
assert FakeWeb.registered_uri?(:get, "http://www.example.com/path")
# check other permutations, too
assert FakeWeb.registered_uri?(:get, "http://www.example.com:80/path")
assert FakeWeb.registered_uri?(:get, "http://www.example.com:8080/path")
assert FakeWeb.registered_uri?(:get, "https://www.example.com:80/path")
assert FakeWeb.registered_uri?(:get, "https://www.example.com:8080/path")
assert !FakeWeb.registered_uri?(:get, "https://www.example.com/path")
end
def test_registry_finds_using_default_port_and_https_when_registered_with_explicit_port_443
FakeWeb.register_uri(:get, %r|example\.com:443|, :body => "example")
assert FakeWeb.registered_uri?(:get, "https://www.example.com/path")
# check other permutations, too
assert FakeWeb.registered_uri?(:get, "https://www.example.com:443/path")
assert FakeWeb.registered_uri?(:get, "https://www.example.com:44321/path")
assert FakeWeb.registered_uri?(:get, "http://www.example.com:443/path")
assert FakeWeb.registered_uri?(:get, "http://www.example.com:44321/path")
assert !FakeWeb.registered_uri?(:get, "http://www.example.com/path")
end
def test_registry_only_finds_using_default_port_when_registered_without_if_protocol_matches
FakeWeb.register_uri(:get, %r|http://www.example.com/test|, :body => "example")
assert FakeWeb.registered_uri?(:get, "http://www.example.com:80/test")
assert !FakeWeb.registered_uri?(:get, "http://www.example.com:443/test")
assert !FakeWeb.registered_uri?(:get, "https://www.example.com:443/test")
FakeWeb.register_uri(:get, %r|https://www.example.org/test|, :body => "example")
assert FakeWeb.registered_uri?(:get, "https://www.example.org:443/test")
assert !FakeWeb.registered_uri?(:get, "https://www.example.org:80/test")
assert !FakeWeb.registered_uri?(:get, "http://www.example.org:80/test")
end
def test_registry_matches_using_mismatched_port_when_registered_without
FakeWeb.register_uri(:get, %r|http://www.example.com|, :body => "example")
assert FakeWeb.registered_uri?(:get, "http://www.example.com:80")
assert FakeWeb.registered_uri?(:get, "http://www.example.com:443")
assert FakeWeb.registered_uri?(:get, "http://www.example.com:12345")
assert !FakeWeb.registered_uri?(:get, "https://www.example.com:443")
assert !FakeWeb.registered_uri?(:get, "https://www.example.com")
end
def test_registry_matches_using_default_port_for_protocol_when_registered_without_protocol_or_port
FakeWeb.register_uri(:get, %r|www.example.com/home|, :body => "example")
assert FakeWeb.registered_uri?(:get, "http://www.example.com/home")
assert FakeWeb.registered_uri?(:get, "https://www.example.com/home")
assert FakeWeb.registered_uri?(:get, "http://www.example.com:80/home")
assert FakeWeb.registered_uri?(:get, "https://www.example.com:443/home")
assert !FakeWeb.registered_uri?(:get, "https://www.example.com:80/home")
assert !FakeWeb.registered_uri?(:get, "http://www.example.com:443/home")
end
def test_registry_matches_with_query_params
FakeWeb.register_uri(:get, %r[example.com/list\?(.*&|)important=1], :body => "example")
assert FakeWeb.registered_uri?(:get, "http://example.com/list?hash=123&important=1&unimportant=2")
assert FakeWeb.registered_uri?(:get, "http://example.com/list?hash=123&important=12&unimportant=2")
assert FakeWeb.registered_uri?(:get, "http://example.com/list?important=1&unimportant=2")
assert !FakeWeb.registered_uri?(:get, "http://example.com/list?important=2")
assert !FakeWeb.registered_uri?(:get, "http://example.com/list?important=2&unimportant=1")
assert !FakeWeb.registered_uri?(:get, "http://example.com/list?hash=123&important=2&unimportant=1")
assert !FakeWeb.registered_uri?(:get, "http://example.com/list?notimportant=1&unimportant=1")
end
def test_registry_does_not_match_when_regex_has_unsorted_query_params
FakeWeb.register_uri(:get, %r[example\.com/list\?b=2&a=1], :body => "example")
assert !FakeWeb.registered_uri?(:get, "http://example.com/list?b=2&a=1")
assert !FakeWeb.registered_uri?(:get, "http://example.com/list?a=1&b=2")
assert !FakeWeb.registered_uri?(:get, "https://example.com:443/list?b=2&a=1")
end
def test_registry_matches_when_regex_has_sorted_query_params
FakeWeb.register_uri(:get, %r[example\.com/list\?a=1&b=2], :body => "example")
assert FakeWeb.registered_uri?(:get, "http://example.com/list?b=2&a=1")
assert FakeWeb.registered_uri?(:get, "http://example.com/list?a=1&b=2")
assert FakeWeb.registered_uri?(:get, "https://example.com:443/list?b=2&a=1")
end
def test_registry_matches_quickly_with_lots_of_query_params
# regression test for code that tried to calculate the permutations of the
# query params, which hangs with a large number of params
FakeWeb.register_uri(:get, %r[example.com], :body => "example")
Timeout::timeout(1) do
FakeWeb.registered_uri?(:get, "http://example.com/?a=1&b=2&c=3&d=4&e=5&f=6&g=7&h=8")
end
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_deprecations.rb 0000644 0001750 0001750 00000003546 13141466106 024057 0 ustar boutil boutil require 'test_helper'
class TestDeprecations < Test::Unit::TestCase
def test_register_uri_without_method_argument_prints_deprecation_warning
warning = capture_stderr do
FakeWeb.register_uri("http://example.com", :body => "test")
end
assert_match %r(deprecation warning: fakeweb)i, warning
end
def test_registered_uri_without_method_argument_prints_deprecation_warning
warning = capture_stderr do
FakeWeb.registered_uri?("http://example.com")
end
assert_match %r(deprecation warning: fakeweb)i, warning
end
def test_response_for_without_method_argument_prints_deprecation_warning
warning = capture_stderr do
FakeWeb.response_for("http://example.com")
end
assert_match %r(deprecation warning: fakeweb)i, warning
end
def test_register_uri_without_method_argument_prints_deprecation_warning_with_correct_caller
warning = capture_stderr do
FakeWeb.register_uri("http://example.com", :body => "test")
end
assert_match %r(Called at.*?test_deprecations\.rb)i, warning
end
def test_register_uri_with_string_option_prints_deprecation_warning
warning = capture_stderr do
FakeWeb.register_uri(:get, "http://example.com", :string => "test")
end
assert_match %r(deprecation warning: fakeweb's :string option)i, warning
end
def test_register_uri_with_file_option_prints_deprecation_warning
warning = capture_stderr do
FakeWeb.register_uri(:get, "http://example.com", :file => fixture_path("test_example.txt"))
end
assert_match %r(deprecation warning: fakeweb's :file option)i, warning
end
def test_register_uri_with_string_option_prints_deprecation_warning_with_correct_caller
warning = capture_stderr do
FakeWeb.register_uri(:get, "http://example.com", :string => "test")
end
assert_match %r(Called at.*?test_deprecations\.rb)i, warning
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/test/test_stub_socket_compatibility.rb 0000644 0001750 0001750 00000003461 13141466106 026651 0 ustar boutil boutil require 'test_helper'
class TestStubSocketCompatibility < Test::Unit::TestCase
def test_sending_timeout_accessors_after_starting_session
# this tests an HTTPS request because #ssl_timeout= raises otherwise
FakeWeb.register_uri(:get, "https://example.com", :status => [200, "OK"])
http = Net::HTTP.new("example.com", 443)
http.use_ssl = true
http.get("/")
timeouts = []
http.methods.grep(/_timeout=/).each do |setter|
http.send(setter, 5)
getter = setter.to_s.sub(/=$/, "")
timeouts << http.send(getter)
end
assert_equal [5], timeouts.uniq
end
def test_stub_socket_always_responds_to_read_timeout
FakeWeb.register_uri(:get, "http://example.com", :status => [200, "OK"])
http = Net::HTTP.new("example.com", 80)
http.get("/")
assert_respond_to http.instance_variable_get(:@socket), :read_timeout=
end
def test_stub_socket_only_responds_to_continue_timeout_under_193_or_later
FakeWeb.register_uri(:get, "http://example.com", :status => [200, "OK"])
http = Net::HTTP.new("example.com", 80)
http.get("/")
socket = http.instance_variable_get(:@socket)
assert_equal RUBY_VERSION >= "1.9.3", socket.respond_to?(:continue_timeout=)
end
def test_stub_socket_responds_to_close_and_always_returns_true
FakeWeb.register_uri(:get, "http://example.com", :status => [200, "OK"])
http = Net::HTTP.new("example.com", 80)
http.get("/")
socket = http.instance_variable_get(:@socket)
assert_equal socket.close, true
end
def test_stub_socket_tracks_closed_state
FakeWeb.register_uri(:get, "http://example.com", :status => [200, "OK"])
http = Net::HTTP.new("example.com", 80)
http.get("/")
socket = http.instance_variable_get(:@socket)
assert !socket.closed?
socket.close
assert socket.closed?
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/README.rdoc 0000644 0001750 0001750 00000017015 13141466106 020636 0 ustar boutil boutil = FakeWeb
FakeWeb is a helper for faking web requests in Ruby. It works at a global
level, without modifying code or writing extensive stubs.
== Installation
* You can install the latest release from RubyGems:
gem install fakeweb
Note that the gem was previously registered as +FakeWeb+, switching
to +fakeweb+ in 2009. All releases are available under the new name.
* If your application uses Bundler, add a line like this to your Gemfile:
gem "fakeweb", "~> 1.3"
You may want to specify :group => :test and/or
:require => false, depending on how you use Bundler.
* If you're developing a gem, add a line like this to your gemspec:
spec.add_development_dependency "fakeweb", ["~> 1.3"]
== Help and discussion
RDocs for the current release are available at http://fakeweb.rubyforge.org.
There's a mailing list for questions and discussion at
https://groups.google.com/d/forum/fakeweb-users.
The main source repository is https://github.com/chrisk/fakeweb.
{
}[https://travis-ci.org/chrisk/fakeweb] FakeWeb's tests run at https://travis-ci.org/chrisk/fakeweb.
== Examples
Start by requiring FakeWeb:
require 'fakeweb'
=== Registering basic string responses
FakeWeb.register_uri(:get, "http://example.com/test1", :body => "Hello World!")
Net::HTTP.get(URI.parse("http://example.com/test1"))
=> "Hello World!"
Net::HTTP.get(URI.parse("http://example.com/test2"))
=> FakeWeb is bypassed and the response from a real request is returned
You can also call register_uri with a regular expression, to match
more than one URI.
FakeWeb.register_uri(:get, %r|http://example\.com/|, :body => "Hello World!")
Net::HTTP.get(URI.parse("http://example.com/test3"))
=> "Hello World!"
=== Replaying a recorded response
page = `curl -is http://www.google.com/`
FakeWeb.register_uri(:get, "http://www.google.com/", :response => page)
Net::HTTP.get(URI.parse("http://www.google.com/"))
# => Full response, including headers
=== Adding a custom status to the response
FakeWeb.register_uri(:get, "http://example.com/", :body => "Nothing to be found 'round here",
:status => ["404", "Not Found"])
Net::HTTP.start("example.com") do |req|
response = req.get("/")
response.code # => "404"
response.message # => "Not Found"
response.body # => "Nothing to be found 'round here"
end
=== Responding to any HTTP method
FakeWeb.register_uri(:any, "http://example.com", :body => "response for any HTTP method")
If you use the :any symbol, the URI you specify will be completely
stubbed out (regardless of the HTTP method of the request). This can be useful
for RPC-style services, where the HTTP method isn't significant. (Older
versions of FakeWeb always behaved like this, and didn't accept the first
+method+ argument above; this syntax is now deprecated.)
=== Rotating responses
You can optionally call FakeWeb.register_uri with an array of options
hashes; these are used, in order, to respond to repeated requests. Once you run
out of responses, further requests always receive the last response. (You can
also send a response more than once before rotating, by specifying a
:times option for that response.)
FakeWeb.register_uri(:delete, "http://example.com/posts/1",
[{:body => "Post 1 deleted.", :status => ["200", "OK"]},
{:body => "Post not found", :status => ["404", "Not Found"]}])
Net::HTTP.start("example.com") do |req|
req.delete("/posts/1").body # => "Post 1 deleted"
req.delete("/posts/1").body # => "Post not found"
req.delete("/posts/1").body # => "Post not found"
end
=== Using HTTP basic authentication
You can fake requests that use basic authentication by adding +userinfo+ strings
to your URIs:
FakeWeb.register_uri(:get, "http://example.com/secret", :body => "Unauthorized", :status => ["401", "Unauthorized"])
FakeWeb.register_uri(:get, "http://user:pass@example.com/secret", :body => "Authorized")
Net::HTTP.start("example.com") do |http|
req = Net::HTTP::Get.new("/secret")
http.request(req) # => "Unauthorized"
req.basic_auth("user", "pass")
http.request(req) # => "Authorized"
end
=== Clearing registered URIs
The FakeWeb registry is a singleton that lasts for the duration of your program,
maintaining every fake response you register. If needed, you can clean out the
registry and remove all registered URIs:
FakeWeb.clean_registry
=== Blocking all real requests
When you're using FakeWeb to replace _all_ of your requests, it's useful to
catch when requests are made for unregistered URIs (unlike the default
behavior, which is to pass those requests through to Net::HTTP as usual).
FakeWeb.allow_net_connect = false
Net::HTTP.get(URI.parse("http://example.com/"))
=> raises FakeWeb::NetConnectNotAllowedError
FakeWeb.allow_net_connect = true
Net::HTTP.get(URI.parse("http://example.com/"))
=> FakeWeb is bypassed and the response from a real request is returned
It's recommended that you set FakeWeb.allow_net_connect = false in the
setup for your tests.
==== Allowing requests to a specific server
If you want to prevent your tests from hitting the internet while allowing
access to a specific server for integration testing, you can assign a URI or
+Regexp+ to be used as a whitelist for outbound requests:
FakeWeb.allow_net_connect = %r[^https?://localhost]
Net::HTTP.get(URI.parse("http://localhost/path")) # => allowed
Net::HTTP.get(URI.parse("http://example.com/")) # => raises FakeWeb::NetConnectNotAllowedError
=== Specifying HTTP response headers
When you register a response using the :body option, you're only
setting the body of the response. If you want to add headers to these responses,
simply add the header as an option to +register_uri+:
FakeWeb.register_uri(:get, "http://example.com/hello.txt", :body => "Hello", :content_type => "text/plain")
This sets the "Content-Type" header in the response.
=== Checking the last request
It's often useful to retrieve the last request made by your code, so you can
write tests for its content. FakeWeb keeps track of the last request, whether it
was stubbed or not:
Net::HTTP.get(URI.parse("http://example.com"))
FakeWeb.last_request # => Net::HTTP::Get request object
== More info
FakeWeb lets you decouple your test environment from live services without
modifying code or writing extensive stubs.
In addition to the conceptual advantage of having idempotent request
behaviour, FakeWeb makes tests run faster than if they were made to remote (or
even local) web servers. It also makes it possible to run tests without a
network connection or in situations where the server is behind a firewall or
has host-based access controls.
FakeWeb works with anything based on Net::HTTP--both higher-level wrappers,
like OpenURI, as well as a ton of libraries for popular web services.
== Known Issues
* Request bodies are ignored, including PUT and POST parameters. If you need
different responses for different request bodies, you need to request
different URLs, and register different responses for each. (Query strings are
fully supported, though.) We're currently considering how the API should
change to add support for request bodies in 1.3.0. Your input would be really
helpful: see https://groups.google.com/d/msg/fakeweb-users/RNGQprEuQnM/ryCiMeBD91YJ
for a discussion of some different options. Thanks!
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/lib/ 0000755 0001750 0001750 00000000000 13141466106 017572 5 ustar boutil boutil ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/lib/fake_web.rb 0000644 0001750 0001750 00000020641 13141466106 021665 0 ustar boutil boutil require 'fake_web/ext/net_http'
require 'fake_web/registry'
require 'fake_web/response'
require 'fake_web/responder'
require 'fake_web/stub_socket'
require 'fake_web/utility'
FakeWeb::Utility.record_loaded_net_http_replacement_libs
FakeWeb::Utility.puts_warning_for_net_http_around_advice_libs_if_needed
module FakeWeb
# Returns the version string for the copy of FakeWeb you have loaded.
VERSION = '1.3.0'
# Resets the FakeWeb Registry. This will force all subsequent web requests to
# behave as real requests.
def self.clean_registry
Registry.instance.clean_registry
end
# Enables or disables real HTTP connections for requests that don't match
# registered URIs.
#
# If you set FakeWeb.allow_net_connect = false and subsequently try
# to make a request to a URI you haven't registered with .register_uri, a
# NetConnectNotAllowedError will be raised. This is handy when you want to
# make sure your tests are self-contained, or want to catch the scenario
# when a URI is changed in implementation code without a corresponding test
# change.
#
# When FakeWeb.allow_net_connect = true (the default), requests to
# URIs not stubbed with FakeWeb are passed through to Net::HTTP.
#
# If you assign a +String+, +URI+, or +Regexp+ object, unstubbed requests
# will be allowed if they match that value. This is useful when you want to
# allow access to a local server for integration testing, while still
# preventing your tests from using the internet.
def self.allow_net_connect=(allowed)
case allowed
when String, URI, Regexp
@allow_all_connections = false
Registry.instance.register_passthrough_uri(allowed)
else
@allow_all_connections = allowed
Registry.instance.remove_passthrough_uri
end
end
# Enable pass-through to Net::HTTP by default.
self.allow_net_connect = true
# Returns +true+ if requests to URIs not registered with FakeWeb are passed
# through to Net::HTTP for normal processing (the default). Returns +false+
# if an exception is raised for these requests.
#
# If you've assigned a +String+, +URI+, or +Regexp+ to
# FakeWeb.allow_net_connect=, you must supply a URI to check
# against that filter. Otherwise, an ArgumentError will be raised.
def self.allow_net_connect?(uri = nil)
if Registry.instance.passthrough_uri_map.any?
raise ArgumentError, "You must supply a URI to test" if uri.nil?
Registry.instance.passthrough_uri_matches?(uri)
else
@allow_all_connections
end
end
# This exception is raised if you set FakeWeb.allow_net_connect =
# false and subsequently try to make a request to a URI you haven't
# stubbed.
class NetConnectNotAllowedError < StandardError; end;
# This exception is raised if a Net::HTTP request matches more than one of
# the stubs you've registered. To fix the problem, remove a duplicate
# registration or disambiguate any regular expressions by making them more
# specific.
class MultipleMatchingURIsError < StandardError; end;
# call-seq:
# FakeWeb.register_uri(method, uri, options)
#
# Register requests using the HTTP method specified by the symbol +method+
# for +uri+ to be handled according to +options+. If you specify the method
# :any, the response will be reigstered for any request for +uri+.
# +uri+ can be a +String+, +URI+, or +Regexp+ object. +options+ must be either
# a +Hash+ or an +Array+ of +Hashes+ (see below), which must contain one of
# these two keys:
#
# :body::
# A string which is used as the body of the response. If the string refers
# to a valid filesystem path, the contents of that file will be read and used
# as the body of the response instead. (This used to be two options,
# :string and :file, respectively. These are now deprecated.)
# :response::
# Either a Net::HTTPResponse, +IO+, +StringIO+, or +String+, which
# is used as the full response for the request.
#
# The easier way by far is to pass the :response option to
# +register_uri+ as a +String+ or an (open for reads) +IO+ object which
# will be used as the complete HTTP response, including headers and body.
# If the string points to a readable file, this file will be used as the
# content for the request.
#
# To obtain a complete response document, you can use the +curl+ command,
# like so:
#
# curl -i http://example.com > response_from_example.com
#
# which can then be used in your test environment like so:
#
# FakeWeb.register_uri(:get, "http://example.com", :response => "response_from_example.com")
#
# See the Net::HTTPResponse
# documentation[http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTPResponse.html]
# for more information on creating custom response objects.
#
# +options+ may also be an +Array+ containing a list of the above-described
# +Hash+. In this case, FakeWeb will rotate through each response. You can
# optionally repeat a response more than once before rotating:
#
# :times::
# The number of times this response will be used before moving on to the
# next one. The last response will be repeated indefinitely, regardless of
# its :times parameter.
#
# Two optional arguments are also accepted:
#
# :status::
# Passing :status as a two-value array will set the response code
# and message. The defaults are 200 and OK, respectively.
# Example:
# FakeWeb.register_uri(:get, "http://example.com", :body => "Go away!", :status => [404, "Not Found"])
# :exception::
# The argument passed via :exception will be raised when the
# specified URL is requested. Any +Exception+ class is valid. Example:
# FakeWeb.register_uri(:get, "http://example.com", :exception => Net::HTTPError)
#
# If you're using the :body response type, you can pass additional
# options to specify the HTTP headers to be used in the response. Example:
#
# FakeWeb.register_uri(:get, "http://example.com/index.txt", :body => "Hello", :content_type => "text/plain")
#
# You can also pass an array of header values to include a header in the
# response more than once:
#
# FakeWeb.register_uri(:get, "http://example.com", :set_cookie => ["name=value", "example=1"])
def self.register_uri(*args)
case args.length
when 3
Registry.instance.register_uri(*args)
when 2
print_missing_http_method_deprecation_warning(*args)
Registry.instance.register_uri(:any, *args)
else
raise ArgumentError.new("wrong number of arguments (#{args.length} for 3)")
end
end
# call-seq:
# FakeWeb.response_for(method, uri)
#
# Returns the faked Net::HTTPResponse object associated with +method+ and +uri+.
def self.response_for(*args, &block) #:nodoc: :yields: response
case args.length
when 2
Registry.instance.response_for(*args, &block)
when 1
print_missing_http_method_deprecation_warning(*args)
Registry.instance.response_for(:any, *args, &block)
else
raise ArgumentError.new("wrong number of arguments (#{args.length} for 2)")
end
end
# call-seq:
# FakeWeb.registered_uri?(method, uri)
#
# Returns true if a +method+ request for +uri+ is registered with FakeWeb.
# Specify a method of :any to check against all HTTP methods.
def self.registered_uri?(*args)
case args.length
when 2
Registry.instance.registered_uri?(*args)
when 1
print_missing_http_method_deprecation_warning(*args)
Registry.instance.registered_uri?(:any, *args)
else
raise ArgumentError.new("wrong number of arguments (#{args.length} for 2)")
end
end
# Returns the request object from the last request made via Net::HTTP.
def self.last_request
@last_request
end
def self.last_request=(request) #:nodoc:
@last_request = request
end
private
def self.print_missing_http_method_deprecation_warning(*args)
method = caller.first.match(/`(.*?)'/)[1]
new_args = args.map { |a| a.inspect }.unshift(":any")
new_args.last.gsub!(/^\{|\}$/, "").gsub!("=>", " => ") if args.last.is_a?(Hash)
$stderr.puts
$stderr.puts "Deprecation warning: FakeWeb requires an HTTP method argument (or use :any). Try this:"
$stderr.puts " FakeWeb.#{method}(#{new_args.join(', ')})"
$stderr.puts "Called at #{caller[1]}"
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/lib/fake_web/ 0000755 0001750 0001750 00000000000 13141466106 021335 5 ustar boutil boutil ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/lib/fake_web/registry.rb 0000644 0001750 0001750 00000007136 13141466106 023541 0 ustar boutil boutil require 'singleton'
module FakeWeb
class Registry #:nodoc:
include Singleton
attr_accessor :uri_map, :passthrough_uri_map
def initialize
clean_registry
end
def clean_registry
self.uri_map = Hash.new { |hash, key| hash[key] = {} }
end
def register_uri(method, uri, options)
uri_map[normalize_uri(uri)][method] = [*[options]].flatten.collect do |option|
if !option.respond_to?(:keys)
raise ArgumentError.new("Expected options hash: #{option.inspect}")
end
FakeWeb::Responder.new(method, uri, option, option[:times])
end
end
def registered_uri?(method, uri)
!responders_for(method, uri).empty?
end
def response_for(method, uri, &block)
responders = responders_for(method, uri)
return nil if responders.empty?
next_responder = responders.last
responders.each do |responder|
if responder.times and responder.times > 0
responder.times -= 1
next_responder = responder
break
end
end
next_responder.response(&block)
end
def register_passthrough_uri(uri)
self.passthrough_uri_map = {normalize_uri(uri) => {:any => true}}
end
def remove_passthrough_uri
self.passthrough_uri_map = {}
end
def passthrough_uri_matches?(uri)
uri = normalize_uri(uri)
uri_map_matches(passthrough_uri_map, :any, uri, URI) ||
uri_map_matches(passthrough_uri_map, :any, uri, Regexp)
end
private
def responders_for(method, uri)
uri = normalize_uri(uri)
uri_map_matches(uri_map, method, uri, URI) ||
uri_map_matches(uri_map, :any, uri, URI) ||
uri_map_matches(uri_map, method, uri, Regexp) ||
uri_map_matches(uri_map, :any, uri, Regexp) ||
[]
end
def uri_map_matches(map, method, uri, type_to_check = URI)
uris_to_check = variations_of_uri_as_strings(uri)
matches = map.select { |registered_uri, method_hash|
registered_uri.is_a?(type_to_check) && method_hash.has_key?(method)
}.select { |registered_uri, method_hash|
if type_to_check == URI
uris_to_check.include?(registered_uri.to_s)
elsif type_to_check == Regexp
uris_to_check.any? { |u| u.match(registered_uri) }
end
}
if matches.size > 1
raise MultipleMatchingURIsError,
"More than one registered URI matched this request: #{method.to_s.upcase} #{uri}"
end
matches.map { |_, method_hash| method_hash[method] }.first
end
def variations_of_uri_as_strings(uri_object)
normalized_uri = normalize_uri(uri_object.dup)
normalized_uri_string = normalized_uri.to_s
variations = [normalized_uri_string]
# if the port is implied in the original, add a copy with an explicit port
if normalized_uri.default_port == normalized_uri.port
variations << normalized_uri_string.sub(
/#{Regexp.escape(normalized_uri.request_uri)}$/,
":#{normalized_uri.port}#{normalized_uri.request_uri}")
end
variations
end
def normalize_uri(uri)
return uri if uri.is_a?(Regexp)
normalized_uri =
case uri
when URI then uri
when String
uri = 'http://' + uri unless uri.match('^https?://')
URI.parse(uri)
end
normalized_uri.query = sort_query_params(normalized_uri.query)
normalized_uri.normalize
end
def sort_query_params(query)
if query.nil? || query.empty?
nil
else
query.split('&').sort.join('&')
end
end
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/lib/fake_web/stub_socket.rb 0000644 0001750 0001750 00000000523 13141466106 024207 0 ustar boutil boutil module FakeWeb
class StubSocket #:nodoc:
Net::BufferedIO.instance_methods.grep(/_timeout$/).each do |timeout|
attr_accessor timeout
end
def initialize(*args)
end
def closed?
@closed ||= false
@closed
end
def close
@closed = true
end
def readuntil(*args)
end
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/lib/fake_web/utility.rb 0000644 0001750 0001750 00000007202 13141466106 023366 0 ustar boutil boutil module FakeWeb
module Utility #:nodoc:
def self.decode_userinfo_from_header(header)
header.sub(/^Basic /, "").unpack("m").first
end
def self.encode_unsafe_chars_in_userinfo(userinfo)
unsafe_in_userinfo = /[^#{URI::REGEXP::PATTERN::UNRESERVED};&=+$,]|^(#{URI::REGEXP::PATTERN::ESCAPED})/
userinfo.split(":").map { |part| uri_escape(part, unsafe_in_userinfo) }.join(":")
end
def self.strip_default_port_from_uri(uri)
case uri
when %r{^http://} then uri.sub(%r{:80(/|$)}, '\1')
when %r{^https://} then uri.sub(%r{:443(/|$)}, '\1')
else uri
end
end
# Returns a string with a normalized version of a Net::HTTP request's URI.
def self.request_uri_as_string(net_http, request)
protocol = net_http.use_ssl? ? "https" : "http"
path = request.path
path = URI.parse(request.path).request_uri if request.path =~ /^http/
if request["authorization"] =~ /^Basic /
userinfo = FakeWeb::Utility.decode_userinfo_from_header(request["authorization"])
userinfo = FakeWeb::Utility.encode_unsafe_chars_in_userinfo(userinfo) + "@"
else
userinfo = ""
end
"#{protocol}://#{userinfo}#{net_http.address}:#{net_http.port}#{path}"
end
# Wrapper that falls back to URI.escape for compatibility with 1.8
def self.uri_escape(*args)
houdini = URI.const_defined?(:Parser) ? URI::Parser.new : URI
houdini.escape(*args)
end
def self.produce_side_effects_of_net_http_request(request, body)
request.set_body_internal(body)
request.content_length = request.body.length unless request.body.nil?
end
def self.io_from_fake_response_object(obj)
case obj
when Socket, OpenSSL::SSL::SSLSocket, StringIO, IO
obj # usable as-is
when String
if !obj.include?("\0") && File.exist?(obj) && !File.directory?(obj)
File.open(obj, "r")
else
StringIO.new(obj)
end
else
raise ArgumentError, "Unable to create fake socket from #{obj}"
end
end
def self.puts_warning_for_net_http_around_advice_libs_if_needed
libs = {"Samuel" => defined?(Samuel)}
warnings = libs.select { |_, loaded| loaded }.map do |name, _|
<<-TEXT.gsub(/ {10}/, '')
\e[1mWarning: FakeWeb was loaded after #{name}\e[0m
* #{name}'s code is being ignored when a request is handled by FakeWeb,
because both libraries work by patching Net::HTTP.
* To fix this, just reorder your requires so that FakeWeb is before #{name}.
TEXT
end
$stderr.puts "\n" + warnings.join("\n") + "\n" if warnings.any?
end
def self.record_loaded_net_http_replacement_libs
libs = {"RightHttpConnection" => defined?(RightHttpConnection)}
@loaded_net_http_replacement_libs = libs.map { |name, loaded| name if loaded }.compact
end
def self.puts_warning_for_net_http_replacement_libs_if_needed
libs = {"RightHttpConnection" => defined?(RightHttpConnection)}
warnings = libs.select { |_, loaded| loaded }.
reject { |name, _| @loaded_net_http_replacement_libs.include?(name) }.
map do |name, _|
<<-TEXT.gsub(/ {10}/, '')
\e[1mWarning: #{name} was loaded after FakeWeb\e[0m
* FakeWeb's code is being ignored, because #{name} replaces parts of
Net::HTTP without deferring to other libraries. This will break Net::HTTP requests.
* To fix this, just reorder your requires so that #{name} is before FakeWeb.
TEXT
end
$stderr.puts "\n" + warnings.join("\n") + "\n" if warnings.any?
end
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/lib/fake_web/responder.rb 0000644 0001750 0001750 00000007563 13141466106 023676 0 ustar boutil boutil module FakeWeb
class Responder #:nodoc:
attr_accessor :method, :uri, :options, :times
KNOWN_OPTIONS = [:body, :exception, :response, :status].freeze
def initialize(method, uri, options, times)
self.method = method
self.uri = uri
self.options = options
self.times = times ? times : 1
if options.has_key?(:file) || options.has_key?(:string)
print_file_string_options_deprecation_warning
options[:body] = options.delete(:file) || options.delete(:string)
end
end
def response(&block)
if has_baked_response?
response = baked_response
else
code, msg = meta_information
response = Net::HTTPResponse.send(:response_class, code.to_s).new("1.0", code.to_s, msg)
response.instance_variable_set(:@body, body)
headers_extracted_from_options.each do |name, value|
if value.respond_to?(:each)
value.each { |v| response.add_field(name, v) }
else
response[name] = value
end
end
end
response.instance_variable_set(:@read, true)
response.extend FakeWeb::Response
optionally_raise(response)
yield response if block_given?
response
end
private
def headers_extracted_from_options
options.reject {|name, _| KNOWN_OPTIONS.include?(name) }.map { |name, value|
[name.to_s.split("_").map { |segment| segment.capitalize }.join("-"), value]
}
end
def body
body = options[:body]
return nil if body.to_s == ''
body = body.to_s if defined?(Pathname) && body.is_a?(Pathname)
if !body.include?("\0") && File.exist?(body) && !File.directory?(body)
File.read(body)
else
body
end
end
def baked_response
response = options[:response]
response = response.to_s if defined?(Pathname) && response.is_a?(Pathname)
if response.is_a?(String) || response.is_a?(IO) || response.is_a?(StringIO)
socket = Net::BufferedIO.new(response)
r = Net::HTTPResponse.read_new(socket)
# Store the original transfer-encoding
saved_transfer_encoding = r.instance_eval {
@header['transfer-encoding'] if @header.key?('transfer-encoding')
}
# Read the body of response
r.instance_eval { @header['transfer-encoding'] = nil }
r.reading_body(socket, true) {}
# Delete the transfer-encoding key from r.@header if there wasn't one;
# otherwise, restore the saved_transfer_encoding
if saved_transfer_encoding.nil?
r.instance_eval { @header.delete('transfer-encoding') }
else
r.instance_eval { @header['transfer-encoding'] = saved_transfer_encoding }
end
r
elsif response.is_a?(Net::HTTPResponse)
response
else
raise ArgumentError, "Handler not implemented for response #{response.inspect}"
end
end
def has_baked_response?
options.has_key?(:response)
end
def optionally_raise(response)
return unless options.has_key?(:exception)
case options[:exception].to_s
when "Net::HTTPError", "OpenURI::HTTPError"
raise options[:exception].new('Exception from FakeWeb', response)
else
raise options[:exception].new('Exception from FakeWeb')
end
end
def meta_information
options.has_key?(:status) ? options[:status] : [200, 'OK']
end
def print_file_string_options_deprecation_warning
which = options.has_key?(:file) ? :file : :string
first_external_caller = caller.detect { |line| !line.include?("/lib/fake_web") }
$stderr.puts
$stderr.puts "Deprecation warning: FakeWeb's :#{which} option has been renamed to :body."
$stderr.puts "Just replace :#{which} with :body in your FakeWeb.register_uri calls."
$stderr.puts "Called at #{first_external_caller}"
end
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/lib/fake_web/ext/ 0000755 0001750 0001750 00000000000 13141466106 022135 5 ustar boutil boutil ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/lib/fake_web/ext/net_http.rb 0000644 0001750 0001750 00000003730 13141466106 024312 0 ustar boutil boutil require 'net/http'
require 'net/https'
require 'stringio'
module Net #:nodoc: all
class BufferedIO
eval <<-RUBY
def initialize_with_fakeweb(*args#{", **opts" if RUBY_VERSION >= "2.4.0" })
initialize_without_fakeweb(*args#{", **opts" if RUBY_VERSION >= "2.4.0" })
@io = FakeWeb::Utility.io_from_fake_response_object(@io)
end
RUBY
alias_method :initialize_without_fakeweb, :initialize
alias_method :initialize, :initialize_with_fakeweb
end
class HTTP
class << self
def socket_type_with_fakeweb
FakeWeb::StubSocket
end
alias_method :socket_type_without_fakeweb, :socket_type
alias_method :socket_type, :socket_type_with_fakeweb
end
def request_with_fakeweb(request, body = nil, &block)
FakeWeb.last_request = request
uri = FakeWeb::Utility.request_uri_as_string(self, request)
method = request.method.downcase.to_sym
if FakeWeb.registered_uri?(method, uri)
@socket = Net::HTTP.socket_type.new
FakeWeb::Utility.produce_side_effects_of_net_http_request(request, body)
FakeWeb.response_for(method, uri, &block)
elsif FakeWeb.allow_net_connect?(uri)
connect_without_fakeweb
request_without_fakeweb(request, body, &block)
else
uri = FakeWeb::Utility.strip_default_port_from_uri(uri)
raise FakeWeb::NetConnectNotAllowedError,
"Real HTTP connections are disabled. Unregistered request: #{request.method} #{uri}"
end
end
alias_method :request_without_fakeweb, :request
alias_method :request, :request_with_fakeweb
def connect_with_fakeweb
unless @@alredy_checked_for_net_http_replacement_libs ||= false
FakeWeb::Utility.puts_warning_for_net_http_replacement_libs_if_needed
@@alredy_checked_for_net_http_replacement_libs = true
end
nil
end
alias_method :connect_without_fakeweb, :connect
alias_method :connect, :connect_with_fakeweb
end
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/lib/fake_web/response.rb 0000644 0001750 0001750 00000000214 13141466106 023515 0 ustar boutil boutil module FakeWeb
module Response #:nodoc:
def read_body(*args, &block)
yield @body if block_given?
@body
end
end
end ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/lib/fakeweb.rb 0000644 0001750 0001750 00000000107 13141466106 021521 0 ustar boutil boutil # So you can require "fakeweb" instead of "fake_web"
require "fake_web" ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/Rakefile 0000644 0001750 0001750 00000004661 13141466106 020500 0 ustar boutil boutil require 'rubygems'
require 'rake'
task :print_header do
version_string = `command -v rvm >/dev/null && rvm current`.strip
version_string = RUBY_DESCRIPTION if !$?.success?
puts "\n# Starting tests using \e[1m#{version_string}\e[0m\n\n"
end
task :check_dependencies do
begin
require "bundler"
rescue LoadError
abort "Error: FakeWeb uses Bundler to manage development dependencies,\n" +
"but it's not installed. Try `gem install bundler`.\n\n"
end
system("bundle check") || abort
end
require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.test_files = FileList["test/**/*.rb"].exclude("test/test_helper.rb",
"test/helpers/**/*",
"test/vendor/**/*")
test.libs << "test"
test.verbose = false
test.warning = true
# To measure code coverage under JRuby, we need to pass --debug (enabling the
# runtime's "full-trace" mode) and --dev (setting its "compile mode" to OFF so
# all code runs through the interpreter). For details, see JRuby's
# util/cli/ArgumentProcessor.java.
test.ruby_opts << "--debug" << "--dev" if RUBY_PLATFORM == "java"
end
Rake::Task["test"].enhance ["test:preflight"]
Rake::Task["test"].clear_comments if Rake::Task["test"].respond_to?(:clear_comments)
Rake::Task["test"].add_description <<-DESC.gsub(/^ /, "")
Run preflight checks, then all tests (default task).
Set COVERAGE_REPORT=1 to produce an HTML-formatted code-coverage
report during the run. It will be written to /coverage.
DESC
namespace :test do
desc "Perform all startup checks without running tests"
task :preflight => [:print_header, :check_dependencies]
end
task :default => :test
desc "Remove build/test/release artifacts"
task :clean do
paths = %w(.rbx/ coverage/ doc/ Gemfile.lock log/ pkg/)
paths.each do |path|
rm_rf File.join(File.dirname(__FILE__), path)
end
end
if RUBY_VERSION >= "1.8.7"
rdoc_options = %w(--show-hash --charset=UTF-8)
begin
require 'sdoc'
rdoc_options += %w(--format sdoc)
rescue LoadError
end
require 'rdoc/task'
Rake::RDocTask.new do |rdoc|
rdoc.title = "FakeWeb 1.3.0 API Documentation"
rdoc.main = "README.rdoc"
rdoc.rdoc_dir = "doc"
rdoc.options += rdoc_options
rdoc.rdoc_files.include("README.rdoc", "CHANGELOG", "LICENSE.txt", "lib/*.rb")
end
else
warn "Warning: RDoc requires ruby >= 1.8.7; doc tasks disabled"
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/Gemfile 0000644 0001750 0001750 00000001260 13141466106 020316 0 ustar boutil boutil source "https://rubygems.org"
gemspec
# Rubinius 2.0 distributes the standard library as gems
platform :rbx do
stdlibs = %w(benchmark cgi coverage delegate erb find logger net-http open-uri
optparse ostruct prettyprint singleton tempfile tmpdir yaml)
stdlibs.each { |lib| gem "rubysl-#{lib}", "~> 2.0" }
# rubysl-test-unit 2.0.2's gemspec relaxed its dependency on minitest to allow
# any version (previously, it specified "~> 4.7"). Minitest 5 doesn't have a
# Test::Unit compatibility layer like 4.x, so it doesn't work with Test::Unit
# at all. rubysl-test-unit 2.0.3 fixed this.
gem "rubysl-test-unit", ["~> 2.0", "!= 2.0.2"]
gem "psych", "~> 2.0"
end
ruby-fakeweb-1.3.0+git20170806+dfsg1.orig/fakeweb.gemspec 0000644 0001750 0001750 00000007231 13141466106 022000 0 ustar boutil boutil # encoding: utf-8
Gem::Specification.new do |s|
s.name = "fakeweb"
s.rubyforge_project = "fakeweb"
s.version = "1.3.0"
s.summary = "A tool for faking responses to HTTP requests"
s.homepage = "https://github.com/chrisk/fakeweb"
s.authors = ["Chris Kampmeier", "Blaine Cook"]
s.email = ["chris@kampers.net", "romeda@gmail.com"]
s.license = "MIT"
s.description = "FakeWeb is a helper for faking web requests in " +
"Ruby. It works at a global level, without " +
"modifying code or writing extensive stubs."
root_docs = %w(CHANGELOG LICENSE.txt README.rdoc)
s.extra_rdoc_files = root_docs
s.files = Dir["lib/**/*.rb"] + root_docs
s.require_paths = ["lib"]
s.rdoc_options = ["--show-hash --charset=UTF-8"]
# Mocha's README says "versions 0.10.2, 0.10.3 & 0.11.0 of the Mocha gem were
# broken. Please do not use these versions."
exclude_broken_mocha_spec = ["!= 0.11.0", "!= 0.10.3", "!= 0.10.2"]
if RUBY_VERSION <= "1.8.6"
# Mocha 0.11.1 introduced a call to #define_method with a block parameter
# (like this: define_method { |*args, &blk| ... }), causing a syntax error
# in 1.8.6. It's still there as of the latest release, 0.13.3. Older
# versions of Mocha work great, though; 0.9.5 is the oldest I've tested so
# far.
mocha_spec = [">= 0.9.5", "< 0.11.1"]
else
# Otherwise, prefer up-to-date Mocha
mocha_spec = ["~> 1.0"]
end
s.add_development_dependency "mocha", mocha_spec + exclude_broken_mocha_spec
# * Rake 0.9.1 had the same syntax error on 1.8.6 as Mocha, but it was fixed
# for the next release.
# * Rake 0.9.6 and 10.0.3 were both released with code using String#end_with?,
# which only works in 1.8.7+; both times, 1.8.6-compatibility was restored
# for the next release.
# * Rake 10.2 and 10.2.1 removed Ruby 1.8 compatibility; 10.2.2 restored it.
# Then Rake 11.0 removed it again for good.
if RUBY_VERSION <= "1.8.6"
rake_spec = [">= 0.8.7", "!= 0.9.1", "!= 0.9.6", "!= 10.0.3",
"!= 10.2", "!= 10.2.1", "< 11.0"]
elsif RUBY_VERSION == "1.8.7"
rake_spec = [">= 0.8.7", "!= 10.2", "!= 10.2.1", "< 11.0"]
elsif RUBY_VERSION < "1.9.3"
# Rake's gemspec started requiring Ruby 1.9.3+ as of 11.0
rake_spec = ["~> 10.0"]
else
# Otherwise, prefer up-to-date Rake
rake_spec = ["~> 12.0"]
end
s.add_development_dependency "rake", rake_spec
if RUBY_VERSION >= "1.8.7"
# ZenTest (autotest) wants at least RubyGems 1.8, which is 1.8.7+
# only, as is RDoc, the main dependency of sdoc.
s.add_development_dependency "ZenTest", ["~> 4.9"]
s.add_development_dependency "sdoc"
# RDoc 4.3.0 only works on Ruby 1.9.3+
if RUBY_VERSION < "1.9.3"
s.add_development_dependency "rdoc", ["< 4.3.0"]
end
end
# To monitor our tests' code coverage, the SimpleCov gem uses Ruby's built-in
# Coverage module, which first shipped with Ruby 1.9.0. SimpleCov doesn't work
# very well on pre-1.9.3, though.
if RUBY_VERSION >= "1.9.3"
s.add_development_dependency "simplecov", ["~> 0.7"]
s.add_development_dependency "simplecov-console", ["~> 0.1"]
# SimpleCov depends on multi_json, which as of 1.7.3 prints a
# warning when the Ruby 1.9 stdlib is the only available backend.
# See https://github.com/intridea/multi_json/commit/e7438e7ba2.
s.add_development_dependency "json", ["~> 1.7"]
end
if RUBY_VERSION >= "2.2.0"
# Test::Unit is no longer distributed with Ruby as of 2.2.0
s.add_development_dependency "test-unit", ["~> 3.2"]
end
end