diff options
Diffstat (limited to 'vendor/gems/fakeweb-1.3.0/lib')
-rw-r--r-- | vendor/gems/fakeweb-1.3.0/lib/fake_web.rb | 215 | ||||
-rw-r--r-- | vendor/gems/fakeweb-1.3.0/lib/fake_web/ext/net_http.rb | 72 | ||||
-rw-r--r-- | vendor/gems/fakeweb-1.3.0/lib/fake_web/registry.rb | 127 | ||||
-rw-r--r-- | vendor/gems/fakeweb-1.3.0/lib/fake_web/responder.rb | 122 | ||||
-rw-r--r-- | vendor/gems/fakeweb-1.3.0/lib/fake_web/response.rb | 10 | ||||
-rw-r--r-- | vendor/gems/fakeweb-1.3.0/lib/fake_web/stub_socket.rb | 15 | ||||
-rw-r--r-- | vendor/gems/fakeweb-1.3.0/lib/fake_web/utility.rb | 87 | ||||
-rw-r--r-- | vendor/gems/fakeweb-1.3.0/lib/fakeweb.rb | 2 |
8 files changed, 650 insertions, 0 deletions
diff --git a/vendor/gems/fakeweb-1.3.0/lib/fake_web.rb b/vendor/gems/fakeweb-1.3.0/lib/fake_web.rb new file mode 100644 index 000000000..77fbdaec4 --- /dev/null +++ b/vendor/gems/fakeweb-1.3.0/lib/fake_web.rb @@ -0,0 +1,215 @@ +require '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 <tt>FakeWeb.allow_net_connect = false</tt> 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 <tt>FakeWeb.allow_net_connect = true</tt> (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 + # <tt>FakeWeb.allow_net_connect=</tt>, 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 <tt>FakeWeb.allow_net_connect = + # false</tt> 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 + # <tt>:any</tt>, 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: + # + # <tt>:body</tt>:: + # 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, + # <tt>:string</tt> and <tt>:file</tt>, respectively. These are now deprecated.) + # <tt>:response</tt>:: + # Either a <tt>Net::HTTPResponse</tt>, an +IO+, or a +String+ which is used + # as the full response for the request. + # + # The easier way by far is to pass the <tt>:response</tt> 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 <tt>Net::HTTPResponse</tt> + # 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: + # + # <tt>:times</tt>:: + # 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 <tt>:times</tt> parameter. + # + # Two optional arguments are also accepted: + # + # <tt>:status</tt>:: + # Passing <tt>:status</tt> as a two-value array will set the response code + # and message. The defaults are <tt>200</tt> and <tt>OK</tt>, respectively. + # Example: + # FakeWeb.register_uri(:get, "http://example.com", :body => "Go away!", :status => [404, "Not Found"]) + # <tt>:exception</tt>:: + # The argument passed via <tt>:exception</tt> 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 <tt>:body</tt> 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 <tt>:any</tt> 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 diff --git a/vendor/gems/fakeweb-1.3.0/lib/fake_web/ext/net_http.rb b/vendor/gems/fakeweb-1.3.0/lib/fake_web/ext/net_http.rb new file mode 100644 index 000000000..4ff3e9a10 --- /dev/null +++ b/vendor/gems/fakeweb-1.3.0/lib/fake_web/ext/net_http.rb @@ -0,0 +1,72 @@ +require '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 diff --git a/vendor/gems/fakeweb-1.3.0/lib/fake_web/registry.rb b/vendor/gems/fakeweb-1.3.0/lib/fake_web/registry.rb new file mode 100644 index 000000000..9a4a34e68 --- /dev/null +++ b/vendor/gems/fakeweb-1.3.0/lib/fake_web/registry.rb @@ -0,0 +1,127 @@ +module FakeWeb + class Registry #:nodoc: + include Singleton + + attr_accessor :uri_map, :passthrough_uri_map + + def initialize + clean_registry + end + + def clean_registry + self.uri_map = Hash.new { |hash, key| hash[key] = {} } + end + + def register_uri(method, uri, options) + uri_map[normalize_uri(uri)][method] = [*[options]].flatten.collect do |option| + 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 diff --git a/vendor/gems/fakeweb-1.3.0/lib/fake_web/responder.rb b/vendor/gems/fakeweb-1.3.0/lib/fake_web/responder.rb new file mode 100644 index 000000000..573fec3d4 --- /dev/null +++ b/vendor/gems/fakeweb-1.3.0/lib/fake_web/responder.rb @@ -0,0 +1,122 @@ +module FakeWeb + class Responder #:nodoc: + + attr_accessor :method, :uri, :options, :times + KNOWN_OPTIONS = [:body, :exception, :response, :status].freeze + + def initialize(method, uri, options, times) + self.method = method + self.uri = uri + self.options = options + self.times = times ? times : 1 + + if options.has_key?(:file) || options.has_key?(:string) + print_file_string_options_deprecation_warning + options[:body] = options.delete(:file) || options.delete(:string) + end + end + + def response(&block) + if has_baked_response? + response = baked_response + else + code, msg = meta_information + response = Net::HTTPResponse.send(:response_class, code.to_s).new("1.0", code.to_s, msg) + response.instance_variable_set(:@body, body) + headers_extracted_from_options.each do |name, value| + if value.respond_to?(:each) + value.each { |v| response.add_field(name, v) } + else + response[name] = value + end + end + end + + response.instance_variable_set(:@read, true) + response.extend FakeWeb::Response + + optionally_raise(response) + + yield response if block_given? + + response + end + + private + + def headers_extracted_from_options + options.reject {|name, _| KNOWN_OPTIONS.include?(name) }.map { |name, value| + [name.to_s.split("_").map { |segment| segment.capitalize }.join("-"), value] + } + end + + def body + 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 +end
\ No newline at end of file diff --git a/vendor/gems/fakeweb-1.3.0/lib/fake_web/response.rb b/vendor/gems/fakeweb-1.3.0/lib/fake_web/response.rb new file mode 100644 index 000000000..41ba2557b --- /dev/null +++ b/vendor/gems/fakeweb-1.3.0/lib/fake_web/response.rb @@ -0,0 +1,10 @@ +module FakeWeb + module Response #:nodoc: + + def read_body(*args, &block) + yield @body if block_given? + @body + end + + end +end
\ No newline at end of file diff --git a/vendor/gems/fakeweb-1.3.0/lib/fake_web/stub_socket.rb b/vendor/gems/fakeweb-1.3.0/lib/fake_web/stub_socket.rb new file mode 100644 index 000000000..008681ca6 --- /dev/null +++ b/vendor/gems/fakeweb-1.3.0/lib/fake_web/stub_socket.rb @@ -0,0 +1,15 @@ +module FakeWeb + class StubSocket #:nodoc: + + def initialize(*args) + end + + def closed? + @closed ||= true + end + + def readuntil(*args) + end + + end +end
\ No newline at end of file diff --git a/vendor/gems/fakeweb-1.3.0/lib/fake_web/utility.rb b/vendor/gems/fakeweb-1.3.0/lib/fake_web/utility.rb new file mode 100644 index 000000000..bd5d7161c --- /dev/null +++ b/vendor/gems/fakeweb-1.3.0/lib/fake_web/utility.rb @@ -0,0 +1,87 @@ +module FakeWeb + module Utility #:nodoc: + + def self.decode_userinfo_from_header(header) + header.sub(/^Basic /, "").unpack("m").first + end + + def self.encode_unsafe_chars_in_userinfo(userinfo) + unsafe_in_userinfo = /[^#{URI::REGEXP::PATTERN::UNRESERVED};&=+$,]|^(#{URI::REGEXP::PATTERN::ESCAPED})/ + userinfo.split(":").map { |part| uri_escape(part, unsafe_in_userinfo) }.join(":") + end + + def self.strip_default_port_from_uri(uri) + case uri + when %r{^http://} then uri.sub(%r{:80(/|$)}, '\1') + when %r{^https://} then uri.sub(%r{:443(/|$)}, '\1') + else uri + end + end + + # Returns a string with a normalized version of a Net::HTTP request's URI. + def self.request_uri_as_string(net_http, request) + protocol = net_http.use_ssl? ? "https" : "http" + + path = request.path + path = URI.parse(request.path).request_uri if request.path =~ /^http/ + + if request["authorization"] =~ /^Basic / + userinfo = FakeWeb::Utility.decode_userinfo_from_header(request["authorization"]) + userinfo = FakeWeb::Utility.encode_unsafe_chars_in_userinfo(userinfo) + "@" + else + userinfo = "" + end + + 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 diff --git a/vendor/gems/fakeweb-1.3.0/lib/fakeweb.rb b/vendor/gems/fakeweb-1.3.0/lib/fakeweb.rb new file mode 100644 index 000000000..6982966bf --- /dev/null +++ b/vendor/gems/fakeweb-1.3.0/lib/fakeweb.rb @@ -0,0 +1,2 @@ +# So you can require "fakeweb" instead of "fake_web" +require "fake_web"
\ No newline at end of file |