-
-
Save capitalist/309177 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'webrick' | |
require 'webrick/httpproxy' | |
require 'fileutils' | |
require 'md5' | |
### | |
# FakeWebRecorder is an HTTP Proxy that records sessions as calls to FakeWeb. | |
# The code that FakeWebRecorder generates should be suitable for testing | |
# interaction with a particular website. | |
# | |
# == Usage | |
# | |
# Run this file directly, then set the proxy of the thing you want recorder to | |
# localhost port 8080. For example, here is a mechanize script that uses | |
# FakeWebRecorder: | |
# | |
# agent = Mechanize.new { |a| | |
# a.set_proxy('localhost', 8080) | |
# } | |
# page = agent.get('http://www.google.com/') | |
# | |
# FakeWebRecorder will dump the fakeweb logs to `pwd`/logs | |
class FakeWebRecorder < WEBrick::HTTPProxyServer | |
def initialize logdir = File.join(File.dirname(__FILE__), 'logs'), port = 8080 | |
@logdir = logdir | |
FileUtils.mkdir_p(@logdir) | |
@fakeweb = File.open(File.join(logdir, 'fakeweb_calls.rb'), 'wb') | |
super( | |
:Port => 8080, | |
:ProxyContentHandler => lambda { |req,res| proxy_content(req, res) }) | |
end | |
def proxy_content req, res | |
filename = File.expand_path( | |
File.join(@logdir, MD5.hexdigest(req.unparsed_uri)[0..5])) | |
verb = req.request_method.downcase.to_sym | |
File.open("#{filename}_body.html", 'wb') { |f| f.write(res.body) } | |
File.open("#{filename}_headers.rb", 'wb') { |f| | |
f.write res.header.inspect | |
} | |
@fakeweb.puts <<-eostub | |
FakeWeb.register_uri( | |
:#{verb}, | |
'#{req.unparsed_uri}', | |
{ | |
:body => File.read('#{filename}_body.html') | |
}.merge(eval(File.read('#{filename}_headers.rb'))) | |
) | |
eostub | |
@fakeweb.flush | |
end | |
end | |
if $0 == __FILE__ | |
server = FakeWebRecorder.new | |
server.start | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment