fakeweb 1.1.2 → 1.2.0

Sign up to get free protection for your applications and to get access to all the features.
data/CHANGELOG CHANGED
@@ -1,30 +1,92 @@
1
+ fakeweb (1.2.0)
2
+
3
+ * add lib/fakeweb.rb so you can require "fakeweb" as well [Chris Kampmeier]
4
+
5
+ * fix compatibility with Ruby 1.9.1 [Chris Kampmeier]
6
+
7
+ * fix that newlines in file-based responses could be doubled in the response
8
+ object's body [Mark Menard, Chris Kampmeier]
9
+
10
+ * fix unnecessary munging of the transfer-encoding header, which improves
11
+ compatibility with mechanize [Mark Menard]
12
+
13
+ * fix a test and the RCov dependency to be compatible with JRuby [Mark Menard]
14
+
15
+ * remove an unnecessary redefinition of OpenURI::HTTPError [Josh Nichols]
16
+
17
+ * rearrange implementation code into separate files, one per class [Josh Nichols]
18
+
19
+ * fix a bug where FakeWeb.response_for would raise if the request wasn't
20
+ registered [Chris Kampmeier]
21
+
22
+ * add HTTP method support, so FakeWeb takes both the URI and method into
23
+ account for registration, requests, and responses. Backwards-compatible with
24
+ the old method signatures, which didn't have a method param. [Chris Kampmeier]
25
+
26
+ * start work on Ruby 1.9 compatibility [Chris Kampmeier]
27
+
28
+ * add FakeWeb.allow_net_connect= to enable/disable the pass-through to
29
+ Net::HTTP for unregistered URIs [Mislav Marohnić, Chris Kampmeier]
30
+
31
+ * remove setup.rb, since most people use RubyGems [Mislav Marohnić]
32
+
33
+ * fix that 'http://example.com/?' (empty query) matches a registered
34
+ 'http://example.com/', and vice-versa [Mislav Marohnić]
35
+
36
+ * improve the test suite to not rely on an internet connection [Chris Kampmeier]
37
+
38
+ * use `rake test` instead of `rake tests` [Josh Nichols]
39
+
40
+ * fix an incompatibility with Ruby 1.8.6 p36 where you'd get "Errno::EINTR:
41
+ Interrupted system call" exceptions in Socket#sysread for any non-faked
42
+ request [Chris Kampmeier]
43
+
44
+ * response rotation: you can now optionally call FakeWeb.register_uri with an
45
+ array of options hashes; these are used, in order, to respond to
46
+ repeated requests (to repeat a response more than once before rotating, use
47
+ the :times option). Once you run out of responses, further requests always
48
+ receive the last response. [Michael Shapiro]
49
+
50
+ * add support for Net::HTTP's undocumented full-URI request style (fixes
51
+ URI::InvalidURIErrors that you might see in older libraries) [Chris Kampmeier]
52
+
53
+ * sort query params before storing internally, so that
54
+ http://example.com/?a=1&b=2 and http://example.com/?b=2&a=1 are considered the
55
+ same URL (although this is technically incorrect, it's much more
56
+ convenient--most web apps work that way, and Net::HTTP's use of a hash to pass
57
+ query params means that the order in which FakeWeb stores them can be
58
+ unpredictable) [Chris Kampmeier]
59
+
60
+ * add support for ports in URLs, so that http://example.com/ and
61
+ http://example.com:3000/ are not the same [Chris Kampmeier]
62
+
63
+ * fix for non-faked SSL requests failing with "Unable to create local socket"
64
+ [Chris Kampmeier]
65
+
66
+ * update Rakefile to fix warning about deprecated code [Chris Kampmeier]
67
+
68
+
1
69
  fakeweb (1.1.2)
2
70
 
3
- [ Blaine Cook ]
4
- * add required dependencies to GemSpec to ensure that tests pass in
5
- firebrigade (http://firebrigade.seattlerb.org/)
71
+ * add required dependencies to GemSpec to ensure that tests pass in firebrigade
72
+ (http://firebrigade.seattlerb.org/) [Blaine Cook]
6
73
 
7
- -- Blaine Cook <romeda@gmail.com> Wed, 31 Aug 2007 17:26:04 -0800
8
74
 
9
75
  fakeweb (1.1.1)
10
76
 
11
- [ Blaine Cook ]
12
- * fix for non-existance of :string method on File as presented by open-uri
13
- * fix for curl example test - google redirects to ccTLDs for those outside US
77
+ * fix for non-existence of :string method on File as presented by open-uri
78
+ [Blaine Cook]
79
+
80
+ * fix for curl example test - google redirects to ccTLDs for those outside US
81
+ [Blaine Cook]
14
82
 
15
- -- Blaine Cook <romeda@gmail.com> Thu, 03 Aug 2006 03:41:48 -0800
16
83
 
17
84
  fakeweb (1.1.0)
18
85
 
19
- [ Blaine Cook ]
20
- * update code to correspond to ruby 1.8.4
21
- * breaks compatibility with ruby 1.8.2
86
+ * update code to correspond to ruby 1.8.4 (breaks compatibility with ruby 1.8.2)
87
+ [Blaine Cook]
22
88
 
23
- -- Blaine Cook <romeda@gmail.com> Tue, 23 May 2006 16:13:26 -0800
24
89
 
25
90
  fakeweb (1.0.0)
26
91
 
27
- [ Blaine Cook ]
28
- * initial import
29
-
30
- -- Blaine Cook <romeda@gmail.com> Mon, 22 May 2006 11:53:42 -0800
92
+ * initial import [Blaine Cook]
File without changes
@@ -0,0 +1,162 @@
1
+ = FakeWeb
2
+
3
+ FakeWeb is a helper for faking web requests in Ruby. It works at a global
4
+ level, without modifying code or writing extensive stubs.
5
+
6
+
7
+ == Installation
8
+
9
+ The latest release of FakeWeb is once again available from your friendly
10
+ RubyForge mirror. Just install the gem:
11
+
12
+ sudo gem install fakeweb
13
+
14
+
15
+ == Help and discussion
16
+
17
+ RDocs for the current release are available at http://fakeweb.rubyforge.org.
18
+
19
+ There's a mailing list for questions and discussion at
20
+ http://groups.google.com/group/fakeweb-users.
21
+
22
+
23
+ == Examples
24
+
25
+ Start by requiring FakeWeb:
26
+
27
+ require 'rubygems'
28
+ require 'fakeweb'
29
+
30
+ === Registering basic string responses
31
+
32
+ FakeWeb.register_uri(:get, "http://example.com/test1", :string => "Hello World!")
33
+
34
+ Net::HTTP.get(URI.parse("http://example.com/test1"))
35
+ => "Hello World!"
36
+
37
+ Net::HTTP.get(URI.parse("http://example.com/test2"))
38
+ => FakeWeb is bypassed and the response from a real request is returned
39
+
40
+ === Replaying a recorded response
41
+
42
+ page = `curl -is http://www.google.com/`
43
+ FakeWeb.register_uri(:get, "http://www.google.com/", :response => page)
44
+
45
+ Net::HTTP.get(URI.parse("http://www.google.com/"))
46
+ # => Full response, including headers
47
+
48
+ === Adding a custom status to the response
49
+
50
+ FakeWeb.register_uri(:get, "http://example.com/", :string => "Nothing to be found 'round here",
51
+ :status => ["404", "Not Found"])
52
+
53
+ Net::HTTP.start("example.com") do |req|
54
+ response = req.get("/")
55
+ response.code # => "404"
56
+ response.message # => "Not Found"
57
+ response.body # => "Nothing to be found 'round here"
58
+ end
59
+
60
+ === Responding to any HTTP method
61
+
62
+ FakeWeb.register_uri(:any, "http://example.com", :string => "response for any HTTP method")
63
+
64
+ If you use the <tt>:any</tt> symbol, the URI you specify will be completely
65
+ stubbed out (regardless of the HTTP method of the request). This can be useful
66
+ for RPC-like services, where the HTTP method isn't significant. (Older
67
+ versions of FakeWeb always behaved like this, and didn't accept the first
68
+ +method+ argument above; this syntax is still supported, for
69
+ backwards-compatibility, but it will probably be deprecated at some point.)
70
+
71
+ === Rotating responses
72
+
73
+ You can optionally call FakeWeb.register_uri with an array of options hashes;
74
+ these are used, in order, to respond to repeated requests. Once you run out of
75
+ responses, further requests always receive the last response. (You can also send
76
+ a response more than once before rotating, by specifying a <tt>:times</tt>
77
+ option for that response.)
78
+
79
+ FakeWeb.register_uri(:delete, "http://example.com/posts/1",
80
+ [{:string => "Post 1 deleted.", :status => ["200", "OK"]},
81
+ {:string => "Post not found", :status => ["404", "Not Found"]}])
82
+
83
+ Net::HTTP.start("example.com") do |req|
84
+ req.delete("/posts/1").body # => "Post 1 deleted"
85
+ req.delete("/posts/1").body # => "Post not found"
86
+ req.delete("/posts/1").body # => "Post not found"
87
+ end
88
+
89
+ === Clearing registered URIs
90
+
91
+ The FakeWeb registry is a singleton that lasts for the duration of your
92
+ program, maintaining every fake response you register. If needed, you
93
+ can clean out the registry and remove all registered URIs:
94
+
95
+ FakeWeb.clean_registry
96
+
97
+ === Blocking all real requests
98
+
99
+ When you're using FakeWeb to replace _all_ of your requests, it's useful to
100
+ catch when requests are made for unregistered URIs (unlike the default
101
+ behavior, which is to pass those requests through to Net::HTTP as usual).
102
+
103
+ FakeWeb.allow_net_connect = false
104
+ Net::HTTP.get(URI.parse("http://example.com/"))
105
+ => raises FakeWeb::NetConnectNotAllowedError
106
+
107
+ FakeWeb.allow_net_connect = true
108
+ Net::HTTP.get(URI.parse("http://example.com/"))
109
+ => FakeWeb is bypassed and the response from a real request is returned
110
+
111
+ This is handy when you want to make sure your tests are self-contained, or you
112
+ want to catch the scenario when a URI is changed in implementation code
113
+ without a corresponding test change.
114
+
115
+
116
+ == More info
117
+
118
+ FakeWeb lets you decouple your test environment from live services without
119
+ modifying code or writing extensive stubs.
120
+
121
+ In addition to the conceptual advantage of having idempotent request
122
+ behaviour, FakeWeb makes tests run faster than if they were made to remote (or
123
+ even local) web servers. It also makes it possible to run tests without a
124
+ network connection or in situations where the server is behind a firewall or
125
+ has host-based access controls.
126
+
127
+ FakeWeb works with anything based on Net::HTTP--both higher-level wrappers,
128
+ like OpenURI, as well as a ton of libraries for popular web services.
129
+
130
+
131
+ == Known Issues
132
+
133
+ * Request bodies are ignored, including PUT and POST parameters. If you need
134
+ different responses for different request bodies, you need to request
135
+ different URLs, and register different responses for each. (Query strings are
136
+ fully supported, though.) We're currently considering how the API should
137
+ change to add support for request bodies in 1.3.0. Your input would be really
138
+ helpful: see http://groups.google.com/group/fakeweb-users/browse_thread/thread/44d190a6b12e4273
139
+ for a discussion of some different options. Thanks!
140
+
141
+
142
+ == Copyright
143
+
144
+ Copyright 2006-2007 Blaine Cook
145
+
146
+ Copyright 2008-2009 various contributors
147
+
148
+ FakeWeb is free software; you can redistribute it and/or modify it under the
149
+ terms of the GNU General Public License as published by the Free Software
150
+ Foundation; either version 2 of the License, or (at your option) any later
151
+ version.
152
+
153
+ FakeWeb is distributed in the hope that it will be useful, but WITHOUT ANY
154
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
155
+ FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
156
+ details.
157
+
158
+ You should have received a copy of the GNU General Public License along
159
+ with FakeWeb; if not, write to the Free Software Foundation, Inc., 51
160
+ Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
161
+
162
+ See <tt>LICENSE.txt</tt> for the full terms.
data/Rakefile CHANGED
@@ -1,69 +1,63 @@
1
- # FakeWeb - Ruby Helper for Faking Web Requests
2
- # Copyright 2006 Blaine Cook <romeda@gmail.com>.
3
- #
4
- # FakeWeb is free software; you can redistribute it and/or modify
5
- # it under the terms of the GNU General Public License as published by
6
- # the Free Software Foundation; either version 2 of the License, or
7
- # (at your option) any later version.
8
- #
9
- # FakeWeb is distributed in the hope that it will be useful,
10
- # but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- # GNU General Public License for more details.
13
- #
14
- # You should have received a copy of the GNU General Public License
15
- # along with FakeWeb; if not, write to the Free Software
16
- # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17
-
18
1
  require 'rubygems'
19
- Gem::manage_gems
20
- require 'rake/gempackagetask'
21
2
  require 'rake/testtask'
22
3
  require 'rake/rdoctask'
23
- require 'rcov/rcovtask'
24
-
25
- spec = Gem::Specification.new do |s|
26
- s.add_dependency('rake')
27
- s.add_dependency('rcov')
28
- s.name = "fakeweb"
29
- s.version = "1.1.2"
30
- s.author = "Blaine Cook"
31
- s.email = "romeda@gmail.com"
32
- s.homepage = "http://fakeweb.rubyforge.org/"
33
- s.platform = Gem::Platform::RUBY
34
- s.summary = "A test helper that makes it simple to test HTTP interaction"
35
- s.files = FileList["{test,lib}/**/*", '[A-Z]*'].exclude("rdoc", ".svn").to_a
36
- s.require_path = "lib"
37
- s.test_files = Dir.glob("test/test_*.rb")
38
- s.has_rdoc = true
39
- s.extra_rdoc_files = ["README", "COPYING"]
40
- s.rubyforge_project = "fakeweb"
41
- end
42
-
43
- Rake::GemPackageTask.new(spec) do |pkg|
44
- pkg.gem_spec = spec
45
- pkg.need_tar = true
46
- pkg.need_zip = true
47
- end
48
4
 
49
- desc "Default Task"
50
- task :default => [:tests]
5
+ task :default => :test
51
6
 
52
7
  desc "Run All Tests"
53
- Rake::TestTask.new :tests do |test|
8
+ Rake::TestTask.new :test do |test|
54
9
  test.test_files = ["test/**/*.rb"]
55
10
  test.verbose = true
56
11
  end
57
12
 
58
13
  desc "Generate Documentation"
59
14
  Rake::RDocTask.new do |rdoc|
60
- rdoc.main = "README"
15
+ rdoc.main = "README.rdoc"
61
16
  rdoc.rdoc_dir = "doc"
62
- rdoc.rdoc_files.include("README", "COPYING", "lib/*.rb")
63
- rdoc.title = "FakeWeb"
17
+ rdoc.rdoc_files.include("README.rdoc", "CHANGELOG", "LICENSE.txt", "lib/*.rb")
18
+ rdoc.title = "FakeWeb API Documentation"
19
+ rdoc.options << '--line-numbers' << '--inline-source'
20
+ rdoc.options << '--charset' << 'utf-8'
64
21
  end
65
22
 
66
- Rcov::RcovTask.new do |t|
67
- t.test_files = FileList['test/**/test*.rb']
68
- t.rcov_opts << "--sort coverage"
23
+ desc %{Update ".manifest" with the latest list of project filenames. Respect\
24
+ .gitignore by excluding everything that git ignores. Update `files` and\
25
+ `test_files` arrays in "*.gemspec" file if it's present.}
26
+ task :manifest do
27
+ list = Dir['**/*'].sort
28
+ spec_file = Dir['*.gemspec'].first
29
+ list -= [spec_file] if spec_file
30
+
31
+ File.read('.gitignore').each_line do |glob|
32
+ glob = glob.chomp.sub(/^\//, '')
33
+ list -= Dir[glob]
34
+ list -= Dir["#{glob}/**/*"] if File.directory?(glob) and !File.symlink?(glob)
35
+ puts "excluding #{glob}"
36
+ end
37
+
38
+ if spec_file
39
+ spec = File.read spec_file
40
+ spec.gsub! /^(\s* s.(test_)?files \s* = \s* )( \[ [^\]]* \] | %w\( [^)]* \) )/mx do
41
+ assignment = $1
42
+ bunch = $2 ? list.grep(/^test\//) : list
43
+ '%s%%w(%s)' % [assignment, bunch.join(' ')]
44
+ end
45
+
46
+ File.open(spec_file, 'w') {|f| f << spec }
47
+ end
48
+ File.open('.manifest', 'w') {|f| f << list.join("\n") }
69
49
  end
50
+
51
+ if RUBY_PLATFORM =~ /java/
52
+ puts "rcov support disabled (running under JRuby)."
53
+ elsif RUBY_VERSION =~ /^1\.9/
54
+ puts "rcov support disabled (running under Ruby 1.9)"
55
+ else
56
+ require 'rcov/rcovtask'
57
+ Rcov::RcovTask.new do |t|
58
+ t.test_files = FileList['test/**/test*.rb']
59
+ t.rcov_opts << "--sort coverage"
60
+ t.rcov_opts << "--exclude gems"
61
+ t.rcov_opts << "--no-validator-links"
62
+ end
63
+ end
@@ -1,44 +1,68 @@
1
- # FakeWeb - Ruby Helper for Faking Web Requests
2
- # Copyright 2006 Blaine Cook <romeda@gmail.com>.
3
- #
4
- # FakeWeb is free software; you can redistribute it and/or modify
5
- # it under the terms of the GNU General Public License as published by
6
- # the Free Software Foundation; either version 2 of the License, or
7
- # (at your option) any later version.
8
- #
9
- # FakeWeb is distributed in the hope that it will be useful,
10
- # but WITHOUT ANY WARRANTY; without even the implied warranty of
11
- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
- # GNU General Public License for more details.
13
- #
14
- # You should have received a copy of the GNU General Public License
15
- # along with FakeWeb; if not, write to the Free Software
16
- # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
17
-
18
- require 'fake_net_http'
19
1
  require 'singleton'
20
2
 
21
- module OpenURI #:nodoc: all
22
- class HTTPError < StandardError; end;
23
- end
3
+ require 'fake_web/ext/net_http'
4
+ require 'fake_web/registry'
5
+ require 'fake_web/response'
6
+ require 'fake_web/responder'
7
+ require 'fake_web/stub_socket'
24
8
 
25
9
  module FakeWeb
26
10
 
27
11
  # Resets the FakeWeb Registry. This will force all subsequent web requests to
28
12
  # behave as real requests.
29
- def FakeWeb.clean_registry; FakeWeb::Registry.instance.clean_registry; end
13
+ def self.clean_registry
14
+ Registry.instance.clean_registry
15
+ end
16
+
17
+ # Enables or disables real HTTP connections for requests that don't match
18
+ # registered URIs.
19
+ #
20
+ # If you set <tt>FakeWeb.allow_net_connect = false</tt> and subsequently try
21
+ # to make a request to a URI you haven't registered with #register_uri, a
22
+ # NetConnectNotAllowedError will be raised. This is handy when you want to
23
+ # make sure your tests are self-contained, or want to catch the scenario
24
+ # when a URI is changed in implementation code without a corresponding test
25
+ # change.
26
+ #
27
+ # When <tt>FakeWeb.allow_net_connect = true</tt> (the default), requests to
28
+ # URIs not stubbed with FakeWeb are passed through to Net::HTTP.
29
+ def self.allow_net_connect=(allowed)
30
+ @allow_net_connect = allowed
31
+ end
32
+
33
+ # Enable pass-through to Net::HTTP by default.
34
+ self.allow_net_connect = true
35
+
36
+ # Returns +true+ if requests to URIs not registered with FakeWeb are passed
37
+ # through to Net::HTTP for normal processing (the default). Returns +false+
38
+ # if an exception is raised for these requests.
39
+ def self.allow_net_connect?
40
+ @allow_net_connect
41
+ end
30
42
 
31
- # Register +uri+ to be handled according to +options+. +uri+ can be a
32
- # +String+ or an +URI+ object. +options+ must be a +Hash+ that must contain
33
- # any one of the following keys:
43
+ # This exception is raised if you set <tt>FakeWeb.allow_net_connect =
44
+ # false</tt> and subsequently try to make a request to a URI you haven't
45
+ # stubbed.
46
+ class NetConnectNotAllowedError < StandardError; end;
47
+
48
+ # call-seq:
49
+ # FakeWeb.register_uri(method, uri, options)
50
+ # FakeWeb.register_uri(uri, options)
51
+ #
52
+ # Register requests using the HTTP method specified by the symbol +method+ for
53
+ # +uri+ to be handled according to +options+. If no +method+ is specified, or
54
+ # you explicitly specify <tt>:any</tt>, the response will be reigstered for
55
+ # any request for +uri+. +uri+ can be a +String+ or a +URI+ object. +options+
56
+ # must be either a +Hash+ or an +Array+ of +Hashes+ (see below) that must
57
+ # contain any one of the following keys:
34
58
  #
35
59
  # <tt>:string</tt>::
36
60
  # Takes a +String+ argument that is returned as the body of the response.
37
- # FakeWeb.register_uri('http://example.com/', :string => "Hello World!")
61
+ # FakeWeb.register_uri(:get, 'http://example.com/', :string => "Hello World!")
38
62
  # <tt>:file</tt>::
39
63
  # Takes a valid filesystem path to a file that is slurped and returned as
40
64
  # the body of the response.
41
- # FakeWeb.register_uri('http://example.com/', :file => "/tmp/my_response_body.txt")
65
+ # FakeWeb.register_uri(:post, 'http://example.com/', :file => "/tmp/my_response_body.txt")
42
66
  # <tt>:response</tt>::
43
67
  # Either an <tt>Net::HTTPResponse</tt>, an +IO+ or a +String+.
44
68
  #
@@ -55,12 +79,20 @@ module FakeWeb
55
79
  #
56
80
  # which can then be used in your test environment like so:
57
81
  #
58
- # FakeWeb.register_uri('http://www.example.com/', :response => 'response_for_www.example.com')
82
+ # FakeWeb.register_uri(:get, 'http://www.example.com/', :response => 'response_for_www.example.com')
59
83
  #
60
84
  # See the <tt>Net::HTTPResponse</tt>
61
85
  # documentation[http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTPResponse.html]
62
86
  # for more information on creating custom response objects.
63
87
  #
88
+ # +options+ may also be an +Array+ containing a list of the above-described +Hash+.
89
+ # In this case, FakeWeb will rotate through each provided response, you may optionally
90
+ # provide:
91
+ #
92
+ # <tt>:times</tt>::
93
+ # The number of times this response will be used. Decremented by one each time it's called.
94
+ # FakeWeb will use the final provided request indefinitely, regardless of its :times parameter.
95
+ #
64
96
  # Two optional arguments are also accepted:
65
97
  #
66
98
  # <tt>:status</tt>::
@@ -73,161 +105,49 @@ module FakeWeb
73
105
  # specified URL is requested. Any +Exception+ class is valid. Example:
74
106
  # FakeWeb.register_uri('http://www.example.com/', :exception => Net::HTTPError)
75
107
  #
76
- def FakeWeb.register_uri(uri, options); FakeWeb::Registry.instance.register_uri(uri, options); end
77
-
78
- # Returns the faked Net::HTTPResponse object associated with +uri+.
79
- def FakeWeb.response_for(uri, &block) #:nodoc: :yields: response
80
- FakeWeb::Registry.instance.response_for(uri, &block)
81
- end
82
-
83
- # Checks for presence of +uri+ in the +FakeWeb+ registry.
84
- def FakeWeb.registered_uri?(uri); FakeWeb::Registry.instance.registered_uri?(uri); end
85
-
86
- class Registry #:nodoc:
87
- include Singleton
88
-
89
- attr_accessor :uri_map
90
-
91
- def initialize
92
- clean_registry
108
+ def self.register_uri(*args)
109
+ method = :any
110
+ case args.length
111
+ when 3 then method, uri, options = *args
112
+ when 2 then uri, options = *args
113
+ else raise ArgumentError.new("wrong number of arguments (#{args.length} for method = :any, uri, options)")
93
114
  end
94
115
 
95
- def clean_registry
96
- self.uri_map = {}
97
- end
98
-
99
- def register_uri(uri, options)
100
- uri_map[normalize_uri(uri)] = FakeWeb::Responder.new(uri, options)
101
- end
102
-
103
- def registered_uri?(uri)
104
- uri_map.has_key?(normalize_uri(uri))
105
- end
106
-
107
- def registered_uri(uri)
108
- uri = normalize_uri(uri)
109
- return uri_map[uri] if registered_uri?(uri)
110
- end
111
-
112
- def response_for(uri, &block)
113
- return registered_uri(uri).response(&block)
114
- end
115
-
116
- private
117
-
118
- def normalize_uri(uri)
119
- case uri
120
- when URI: uri
121
- else
122
- uri = 'http://' + uri unless uri.match('^https?://')
123
- URI.parse(uri)
124
- end
125
- end
126
- end
127
-
128
- module Response #:nodoc:
129
- def read_body(*args, &block)
130
- yield @body if block_given?
131
- @body
132
- end
116
+ Registry.instance.register_uri(method, uri, options)
133
117
  end
134
118
 
135
- class Responder #:nodoc:
136
-
137
- attr_accessor :uri, :options
138
-
139
- def initialize(uri, options)
140
- self.uri = uri
141
- self.options = options
142
- end
143
-
144
- def response(&block)
145
- if has_baked_response?
146
- response = baked_response
147
- else
148
- code, msg = meta_information
149
- response = Net::HTTPResponse.send(:response_class, code.to_s).new(uri, code.to_s, msg)
150
- response.instance_variable_set(:@body, content)
151
- end
152
- response.instance_variable_set(:@read, true)
153
- response.extend FakeWeb::Response
154
-
155
- optionally_raise(response)
156
-
157
- yield response if block_given?
158
-
159
- response
160
- end
161
-
162
- private
163
-
164
- def content
165
- [ :file, :string ].each do |map_option|
166
- next unless options.has_key?(map_option)
167
- return self.send("#{map_option}_response", options[map_option])
168
- end
169
-
170
- return ''
171
- end
172
-
173
- def file_response(path)
174
- IO.readlines(path).join("\n")
175
- end
176
-
177
- def string_response(string)
178
- string
179
- end
180
-
181
- def baked_response
182
- resp = case options[:response]
183
- when Net::HTTPResponse: options[:response]
184
- when String
185
- socket = Net::BufferedIO.new(options[:response])
186
- r = Net::HTTPResponse.read_new(socket)
187
- r.instance_eval { @header['transfer-encoding'] = nil }
188
- r.reading_body(socket, true) {}
189
- r
190
- else raise StandardError, "Handler unimplemented for response #{options[:response]}"
191
- end
192
- end
193
-
194
- def has_baked_response?
195
- options.has_key?(:response)
196
- end
197
-
198
- def optionally_raise(response)
199
- return unless options.has_key?(:exception)
200
- ex_alloc = options[:exception].allocate
201
- ex_instance = case ex_alloc
202
- when Net::HTTPError, OpenURI::HTTPError: options[:exception].new('Exception from FakeWeb', response)
203
- else options[:exception].new
204
- end
205
- raise ex_instance
119
+ # call-seq:
120
+ # FakeWeb.response_for(method, uri)
121
+ # FakeWeb.response_for(uri)
122
+ #
123
+ # Returns the faked Net::HTTPResponse object associated with +uri+.
124
+ def self.response_for(*args, &block) #:nodoc: :yields: response
125
+ method = :any
126
+ case args.length
127
+ when 2 then method, uri = args
128
+ when 1 then uri = args.first
129
+ else raise ArgumentError.new("wrong number of arguments (#{args.length} for method = :any, uri)")
206
130
  end
207
131
 
208
- def meta_information
209
- if options.has_key?(:status); options[:status]
210
- else; [ 200, 'OK' ]
211
- end
212
- end
132
+ Registry.instance.response_for(method, uri, &block)
213
133
  end
214
134
 
215
- class SocketDelegator #:nodoc:
216
-
217
- def initialize(delegate=nil)
218
- @delegate = nil
219
- end
220
-
221
- def method_missing(method, *args, &block)
222
- return @delegate.send(method, *args, &block) if @delegate
223
- return self.send("my_#{method}", *args, &block)
224
- end
225
-
226
- def my_closed?
227
- @closed ||= true
228
- end
229
-
230
- def my_readuntil(*args)
231
- end
135
+ # call-seq:
136
+ # FakeWeb.registered_uri?(method, uri)
137
+ # FakeWeb.registered_uri?(uri)
138
+ #
139
+ # Returns true if +uri+ is registered with FakeWeb. You can optionally
140
+ # specify +method+ to limit the search to a certain HTTP method (or use
141
+ # <tt>:any</tt> to explicitly check against any method).
142
+ def self.registered_uri?(*args)
143
+ method = :any
144
+ case args.length
145
+ when 2 then method, uri = args
146
+ when 1 then uri = args.first
147
+ else raise ArgumentError.new("wrong number of arguments (#{args.length} for method = :any, uri)")
148
+ end
149
+
150
+ Registry.instance.registered_uri?(method, uri)
232
151
  end
233
- end
152
+
153
+ end