ruby-fakeweb-1.3.0+dfsg1.orig/0000755000175000017500000000000012223477177015427 5ustar boutilboutilruby-fakeweb-1.3.0+dfsg1.orig/fakeweb.gemspec0000644000175000017500000001134412223477177020403 0ustar boutilboutil# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{fakeweb} s.version = "1.3.0" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Chris Kampmeier", "Blaine Cook"] s.date = %q{2010-08-22} s.description = %q{FakeWeb is a helper for faking web requests in Ruby. It works at a global level, without modifying code or writing extensive stubs.} s.email = ["chris@kampers.net", "romeda@gmail.com"] s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc" ] s.files = [ ".autotest", ".gitignore", "CHANGELOG", "LICENSE.txt", "README.rdoc", "Rakefile", "fakeweb.gemspec", "lib/fake_web.rb", "lib/fake_web/ext/net_http.rb", "lib/fake_web/registry.rb", "lib/fake_web/responder.rb", "lib/fake_web/response.rb", "lib/fake_web/stub_socket.rb", "lib/fake_web/utility.rb", "lib/fakeweb.rb", "test/fixtures/google_response_from_curl", "test/fixtures/google_response_with_transfer_encoding", "test/fixtures/google_response_without_transfer_encoding", "test/fixtures/test_example.txt", "test/fixtures/test_txt_file", "test/test_allow_net_connect.rb", "test/test_deprecations.rb", "test/test_fake_authentication.rb", "test/test_fake_web.rb", "test/test_fake_web_open_uri.rb", "test/test_helper.rb", "test/test_last_request.rb", "test/test_missing_open_uri.rb", "test/test_missing_pathname.rb", "test/test_other_net_http_libraries.rb", "test/test_precedence.rb", "test/test_query_string.rb", "test/test_regexes.rb", "test/test_response_headers.rb", "test/test_trailing_slashes.rb", "test/test_utility.rb", "test/vendor/right_http_connection-1.2.4/History.txt", "test/vendor/right_http_connection-1.2.4/Manifest.txt", "test/vendor/right_http_connection-1.2.4/README.txt", "test/vendor/right_http_connection-1.2.4/Rakefile", "test/vendor/right_http_connection-1.2.4/lib/net_fix.rb", "test/vendor/right_http_connection-1.2.4/lib/right_http_connection.rb", "test/vendor/right_http_connection-1.2.4/setup.rb", "test/vendor/samuel-0.2.1/.document", "test/vendor/samuel-0.2.1/.gitignore", "test/vendor/samuel-0.2.1/LICENSE", "test/vendor/samuel-0.2.1/README.rdoc", "test/vendor/samuel-0.2.1/Rakefile", "test/vendor/samuel-0.2.1/VERSION", "test/vendor/samuel-0.2.1/lib/samuel.rb", "test/vendor/samuel-0.2.1/lib/samuel/net_http.rb", "test/vendor/samuel-0.2.1/lib/samuel/request.rb", "test/vendor/samuel-0.2.1/samuel.gemspec", "test/vendor/samuel-0.2.1/test/request_test.rb", "test/vendor/samuel-0.2.1/test/samuel_test.rb", "test/vendor/samuel-0.2.1/test/test_helper.rb", "test/vendor/samuel-0.2.1/test/thread_test.rb" ] s.homepage = %q{http://github.com/chrisk/fakeweb} s.rdoc_options = ["--charset=UTF-8"] s.require_paths = ["lib"] s.rubyforge_project = %q{fakeweb} s.rubygems_version = %q{1.3.7} s.summary = %q{A tool for faking responses to HTTP requests} s.test_files = [ "test/test_allow_net_connect.rb", "test/test_deprecations.rb", "test/test_fake_authentication.rb", "test/test_fake_web.rb", "test/test_fake_web_open_uri.rb", "test/test_helper.rb", "test/test_last_request.rb", "test/test_missing_open_uri.rb", "test/test_missing_pathname.rb", "test/test_other_net_http_libraries.rb", "test/test_precedence.rb", "test/test_query_string.rb", "test/test_regexes.rb", "test/test_response_headers.rb", "test/test_trailing_slashes.rb", "test/test_utility.rb", "test/vendor/right_http_connection-1.2.4/lib/net_fix.rb", "test/vendor/right_http_connection-1.2.4/lib/right_http_connection.rb", "test/vendor/right_http_connection-1.2.4/setup.rb", "test/vendor/samuel-0.2.1/lib/samuel/net_http.rb", "test/vendor/samuel-0.2.1/lib/samuel/request.rb", "test/vendor/samuel-0.2.1/lib/samuel.rb", "test/vendor/samuel-0.2.1/test/request_test.rb", "test/vendor/samuel-0.2.1/test/samuel_test.rb", "test/vendor/samuel-0.2.1/test/test_helper.rb", "test/vendor/samuel-0.2.1/test/thread_test.rb" ] if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q, [">= 0.9.5"]) else s.add_dependency(%q, [">= 0.9.5"]) end else s.add_dependency(%q, [">= 0.9.5"]) end end ruby-fakeweb-1.3.0+dfsg1.orig/README.rdoc0000644000175000017500000001575412223477177017251 0ustar boutilboutil= 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 gem install fakeweb Note: the gem was previously available as +FakeWeb+ (capital letters), but now all versions are simply registered as +fakeweb+. If you have any old +FakeWeb+ gems lying around, remove them: gem uninstall FakeWeb == 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 http://groups.google.com/group/fakeweb-users. The main source repository is http://github.com/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 http://groups.google.com/group/fakeweb-users/browse_thread/thread/44d190a6b12e4273 for a discussion of some different options. Thanks! ruby-fakeweb-1.3.0+dfsg1.orig/.gitignore0000644000175000017500000000005512223477177017417 0ustar boutilboutil/doc /rdoc /html /coverage /pkg /.idea *.rbc ruby-fakeweb-1.3.0+dfsg1.orig/Rakefile0000644000175000017500000000365412223477177017104 0ustar boutilboutilrequire 'rubygems' require 'rake' version = '1.3.0' begin require 'jeweler' Jeweler::Tasks.new do |gem| gem.name = "fakeweb" gem.rubyforge_project = "fakeweb" gem.version = version gem.summary = "A tool for faking responses to HTTP requests" gem.description = "FakeWeb is a helper for faking web requests in Ruby. It works at a global level, without modifying code or writing extensive stubs." gem.email = ["chris@kampers.net", "romeda@gmail.com"] gem.authors = ["Chris Kampmeier", "Blaine Cook"] gem.homepage = "http://github.com/chrisk/fakeweb" gem.add_development_dependency "mocha", ">= 0.9.5" end rescue LoadError puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler" end require 'rake/testtask' Rake::TestTask.new(:test) do |test| test.test_files = FileList["test/**/*.rb"].exclude("test/test_helper.rb", "test/vendor") test.libs << "test" test.verbose = false test.warning = true end task :default => [:check_dependencies, :test] begin require 'rcov/rcovtask' Rcov::RcovTask.new do |t| t.test_files = FileList["test/**/*.rb"].exclude("test/test_helper.rb", "test/vendor") t.libs << "test" t.rcov_opts << "--sort coverage" t.rcov_opts << "--exclude gems" t.warning = true end rescue LoadError print "rcov support disabled " if RUBY_PLATFORM =~ /java/ puts "(running under JRuby)" else puts "(install RCov to enable the `rcov` task)" end end begin require 'sdoc' require 'rdoc/task' Rake::RDocTask.new do |rdoc| rdoc.main = "README.rdoc" rdoc.rdoc_files.include("README.rdoc", "CHANGELOG", "LICENSE.txt", "lib/*.rb") rdoc.title = "FakeWeb #{version} API Documentation" rdoc.rdoc_dir = "doc" rdoc.template = "direct" rdoc.options << "--line-numbers" << "--show-hash" << "--charset=utf-8" end rescue LoadError puts "SDoc (or a dependency) not available. Install it with: gem install sdoc" end ruby-fakeweb-1.3.0+dfsg1.orig/LICENSE.txt0000644000175000017500000000211112223477177017245 0ustar boutilboutilCopyright 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+dfsg1.orig/.autotest0000644000175000017500000000020212223477177017272 0ustar boutilboutilAutotest.add_hook :initialize do |autotest| %w(.git vendor).each do |directory| autotest.add_exception(directory) end end ruby-fakeweb-1.3.0+dfsg1.orig/test/0000755000175000017500000000000012223560071016370 5ustar boutilboutilruby-fakeweb-1.3.0+dfsg1.orig/test/test_other_net_http_libraries.rb0000644000175000017500000000270112223477177025054 0ustar boutilboutilrequire 'test_helper' class TestOtherNetHttpLibraries < Test::Unit::TestCase def capture_output_from_requiring(libs, additional_code = "") requires = libs.map { |lib| "require '#{lib}'" }.join("; ") fakeweb_dir = "#{File.dirname(__FILE__)}/../lib" vendor_dirs = Dir["#{File.dirname(__FILE__)}/vendor/*/lib"] load_path_opts = vendor_dirs.unshift(fakeweb_dir).map { |dir| "-I#{dir}" }.join(" ") `#{ruby_path} #{load_path_opts} -e "#{requires}; #{additional_code}" 2>&1` 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 output.empty? 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 output.empty? 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+dfsg1.orig/test/test_fake_web.rb0000644000175000017500000005765712223477177021561 0ustar boutilboutilrequire '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_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_without_domain_name assert_raises URI::InvalidURIError do FakeWeb.register_uri(:get, 'test_example2.txt', fixture_path("test_example.txt")) 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) assert_raises StandardError do Net::HTTP.start('mock') { |q| q.get('/unimplemented') } end end def test_specifying_nil_for_body FakeWeb.register_uri(:head, "http://example.com", :body => nil) response = Net::HTTP.start("example.com") { |query| query.head("/") } assert_equal "", 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 body = 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_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_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+dfsg1.orig/test/test_query_string.rb0000644000175000017500000000351512223477177022531 0ustar boutilboutilrequire '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+dfsg1.orig/test/test_allow_net_connect.rb0000644000175000017500000001521712223477177023475 0ustar boutilboutilrequire '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+dfsg1.orig/test/test_trailing_slashes.rb0000644000175000017500000000424612223477177023333 0ustar boutilboutilrequire '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 response = 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 response = Net::HTTP.start("www.example.com") { |query| query.get('/users') } end end end ruby-fakeweb-1.3.0+dfsg1.orig/test/fixtures/0000755000175000017500000000000012223560071020241 5ustar boutilboutilruby-fakeweb-1.3.0+dfsg1.orig/test/fixtures/test_txt_file0000644000175000017500000000002412223477177023053 0ustar boutilboutilline 1 line 2 line 3ruby-fakeweb-1.3.0+dfsg1.orig/test/fixtures/test_example.txt0000644000175000017500000000002412223477177023506 0ustar boutilboutiltest example contentruby-fakeweb-1.3.0+dfsg1.orig/test/test_deprecations.rb0000644000175000017500000000354612223477177022462 0ustar boutilboutilrequire '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+dfsg1.orig/test/test_missing_open_uri.rb0000644000175000017500000000110712223477177023342 0ustar boutilboutilrequire '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+dfsg1.orig/test/test_utility.rb0000644000175000017500000000650612223477177021504 0ustar boutilboutilrequire '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+dfsg1.orig/test/test_fake_web_open_uri.rb0000644000175000017500000000430412223477177023436 0ustar boutilboutilrequire '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+dfsg1.orig/test/test_last_request.rb0000644000175000017500000000226312223477177022510 0ustar boutilboutilrequire '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+dfsg1.orig/test/test_response_headers.rb0000644000175000017500000000774212223477177023335 0ustar boutilboutilrequire '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+dfsg1.orig/test/test_helper.rb0000644000175000017500000000637112223477177021260 0ustar boutilboutilrequire 'test/unit' require 'open-uri' require 'pathname' require 'fake_web' require 'rbconfig' require 'rubygems' require 'mocha' # 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 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 # 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) socket.expects(:connect).with().at_least_once else socket = mock("TCPSocket") Socket.expects(:===).with(socket).at_least_once.returns(true) end TCPSocket.expects(:open).with(options[:host], options[:port]).returns(socket).at_least_once 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 read_method = RUBY_VERSION >= "1.9.2" ? :read_nonblock : :sysread 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+dfsg1.orig/test/test_fake_authentication.rb0000644000175000017500000000726012223477177024004 0ustar boutilboutilrequire '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+dfsg1.orig/test/test_precedence.rb0000644000175000017500000000752612223477177022101 0ustar boutilboutilrequire '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+dfsg1.orig/test/test_regexes.rb0000644000175000017500000002030412223477177021433 0ustar boutilboutilrequire '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+dfsg1.orig/test/test_missing_pathname.rb0000644000175000017500000000217612223477177023326 0ustar boutilboutilrequire '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_raise StandardError do Net::HTTP.start("example.com") { |http| http.get("/") } end end end ruby-fakeweb-1.3.0+dfsg1.orig/CHANGELOG0000644000175000017500000001741312223477177016647 0ustar boutilboutilfakeweb (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+dfsg1.orig/lib/0000755000175000017500000000000012223477177016175 5ustar boutilboutilruby-fakeweb-1.3.0+dfsg1.orig/lib/fakeweb.rb0000644000175000017500000000010712223477177020124 0ustar boutilboutil# So you can require "fakeweb" instead of "fake_web" require "fake_web"ruby-fakeweb-1.3.0+dfsg1.orig/lib/fake_web/0000755000175000017500000000000012223477177017740 5ustar boutilboutilruby-fakeweb-1.3.0+dfsg1.orig/lib/fake_web/stub_socket.rb0000644000175000017500000000025212223477177022611 0ustar boutilboutilmodule FakeWeb class StubSocket #:nodoc: def initialize(*args) end def closed? @closed ||= true end def readuntil(*args) end end endruby-fakeweb-1.3.0+dfsg1.orig/lib/fake_web/utility.rb0000644000175000017500000000644412223477177022000 0ustar boutilboutilmodule 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 uri = "#{protocol}://#{userinfo}#{net_http.address}:#{net_http.port}#{path}" end # Wrapper for URI escaping that switches between URI::Parser#escape and # URI.escape for 1.9-compatibility def self.uri_escape(*args) if URI.const_defined?(:Parser) URI::Parser.new.escape(*args) else URI.escape(*args) end 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.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+dfsg1.orig/lib/fake_web/response.rb0000644000175000017500000000021412223477177022120 0ustar boutilboutilmodule FakeWeb module Response #:nodoc: def read_body(*args, &block) yield @body if block_given? @body end end endruby-fakeweb-1.3.0+dfsg1.orig/lib/fake_web/ext/0000755000175000017500000000000012223477177020540 5ustar boutilboutilruby-fakeweb-1.3.0+dfsg1.orig/lib/fake_web/ext/net_http.rb0000644000175000017500000000423112223477177022712 0ustar boutilboutilrequire 'net/http' require 'net/https' require 'stringio' module Net #:nodoc: all class BufferedIO def initialize_with_fakeweb(io, debug_output = nil) @read_timeout = 60 @rbuf = '' @debug_output = debug_output @io = case io when Socket, OpenSSL::SSL::SSLSocket, IO io when String if !io.include?("\0") && File.exists?(io) && !File.directory?(io) File.open(io, "r") else StringIO.new(io) end end raise "Unable to create local socket" unless @io end 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+dfsg1.orig/lib/fake_web/registry.rb0000644000175000017500000000671112223477177022142 0ustar boutilboutilmodule 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| 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+dfsg1.orig/lib/fake_web/responder.rb0000644000175000017500000000740712223477177022276 0ustar boutilboutilmodule 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 return '' if options[:body].nil? options[:body] = options[:body].to_s if defined?(Pathname) && options[:body].is_a?(Pathname) if !options[:body].include?("\0") && File.exists?(options[:body]) && !File.directory?(options[:body]) File.read(options[:body]) else options[:body] end end def baked_response return options[:response] if options[:response].is_a?(Net::HTTPResponse) if options[:response].is_a?(String) || (defined?(Pathname) && options[:response].is_a?(Pathname)) socket = Net::BufferedIO.new(options[:response].to_s) 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 else raise StandardError, "Handler unimplemented for response #{options[:response]}" 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 $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 #{caller[6]}" end end endruby-fakeweb-1.3.0+dfsg1.orig/lib/fake_web.rb0000644000175000017500000002066512223477177020276 0ustar boutilboutilrequire 'singleton' 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, an +IO+, or a +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+dfsg1.orig/metadata.yml0000644000175000017500000001101312223477177017726 0ustar boutilboutil--- !ruby/object:Gem::Specification name: fakeweb version: !ruby/object:Gem::Version hash: 27 prerelease: false segments: - 1 - 3 - 0 version: 1.3.0 platform: ruby authors: - Chris Kampmeier - Blaine Cook autorequire: bindir: bin cert_chain: [] date: 2010-08-22 00:00:00 -07:00 default_executable: dependencies: - !ruby/object:Gem::Dependency name: mocha prerelease: false requirement: &id001 !ruby/object:Gem::Requirement none: false requirements: - - ">=" - !ruby/object:Gem::Version hash: 49 segments: - 0 - 9 - 5 version: 0.9.5 type: :development version_requirements: *id001 description: FakeWeb is a helper for faking web requests in Ruby. It works at a global level, without modifying code or writing extensive stubs. email: - chris@kampers.net - romeda@gmail.com executables: [] extensions: [] extra_rdoc_files: - LICENSE.txt - README.rdoc files: - .autotest - .gitignore - CHANGELOG - LICENSE.txt - README.rdoc - Rakefile - fakeweb.gemspec - lib/fake_web.rb - lib/fake_web/ext/net_http.rb - lib/fake_web/registry.rb - lib/fake_web/responder.rb - lib/fake_web/response.rb - lib/fake_web/stub_socket.rb - lib/fake_web/utility.rb - lib/fakeweb.rb - test/fixtures/google_response_from_curl - test/fixtures/google_response_with_transfer_encoding - test/fixtures/google_response_without_transfer_encoding - test/fixtures/test_example.txt - test/fixtures/test_txt_file - test/test_allow_net_connect.rb - test/test_deprecations.rb - test/test_fake_authentication.rb - test/test_fake_web.rb - test/test_fake_web_open_uri.rb - test/test_helper.rb - test/test_last_request.rb - test/test_missing_open_uri.rb - test/test_missing_pathname.rb - test/test_other_net_http_libraries.rb - test/test_precedence.rb - test/test_query_string.rb - test/test_regexes.rb - test/test_response_headers.rb - test/test_trailing_slashes.rb - test/test_utility.rb - test/vendor/right_http_connection-1.2.4/History.txt - test/vendor/right_http_connection-1.2.4/Manifest.txt - test/vendor/right_http_connection-1.2.4/README.txt - test/vendor/right_http_connection-1.2.4/Rakefile - test/vendor/right_http_connection-1.2.4/lib/net_fix.rb - test/vendor/right_http_connection-1.2.4/lib/right_http_connection.rb - test/vendor/right_http_connection-1.2.4/setup.rb - test/vendor/samuel-0.2.1/.document - test/vendor/samuel-0.2.1/.gitignore - test/vendor/samuel-0.2.1/LICENSE - test/vendor/samuel-0.2.1/README.rdoc - test/vendor/samuel-0.2.1/Rakefile - test/vendor/samuel-0.2.1/VERSION - test/vendor/samuel-0.2.1/lib/samuel.rb - test/vendor/samuel-0.2.1/lib/samuel/net_http.rb - test/vendor/samuel-0.2.1/lib/samuel/request.rb - test/vendor/samuel-0.2.1/samuel.gemspec - test/vendor/samuel-0.2.1/test/request_test.rb - test/vendor/samuel-0.2.1/test/samuel_test.rb - test/vendor/samuel-0.2.1/test/test_helper.rb - test/vendor/samuel-0.2.1/test/thread_test.rb has_rdoc: true homepage: http://github.com/chrisk/fakeweb licenses: [] post_install_message: rdoc_options: - --charset=UTF-8 require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement none: false requirements: - - ">=" - !ruby/object:Gem::Version hash: 3 segments: - 0 version: "0" required_rubygems_version: !ruby/object:Gem::Requirement none: false requirements: - - ">=" - !ruby/object:Gem::Version hash: 3 segments: - 0 version: "0" requirements: [] rubyforge_project: fakeweb rubygems_version: 1.3.7 signing_key: specification_version: 3 summary: A tool for faking responses to HTTP requests test_files: - test/test_allow_net_connect.rb - test/test_deprecations.rb - test/test_fake_authentication.rb - test/test_fake_web.rb - test/test_fake_web_open_uri.rb - test/test_helper.rb - test/test_last_request.rb - test/test_missing_open_uri.rb - test/test_missing_pathname.rb - test/test_other_net_http_libraries.rb - test/test_precedence.rb - test/test_query_string.rb - test/test_regexes.rb - test/test_response_headers.rb - test/test_trailing_slashes.rb - test/test_utility.rb - test/vendor/right_http_connection-1.2.4/lib/net_fix.rb - test/vendor/right_http_connection-1.2.4/lib/right_http_connection.rb - test/vendor/right_http_connection-1.2.4/setup.rb - test/vendor/samuel-0.2.1/lib/samuel/net_http.rb - test/vendor/samuel-0.2.1/lib/samuel/request.rb - test/vendor/samuel-0.2.1/lib/samuel.rb - test/vendor/samuel-0.2.1/test/request_test.rb - test/vendor/samuel-0.2.1/test/samuel_test.rb - test/vendor/samuel-0.2.1/test/test_helper.rb - test/vendor/samuel-0.2.1/test/thread_test.rb