teamcapybara--capybara/lib/capybara/server.rb

101 lines
2.1 KiB
Ruby
Raw Normal View History

require 'uri'
2009-11-05 16:35:45 +00:00
require 'net/http'
2009-11-05 16:39:57 +00:00
require 'rack'
2009-11-05 16:35:45 +00:00
2009-11-16 21:02:16 +00:00
class Capybara::Server
class Identify
def initialize(app)
@app = app
end
def call(env)
if env["PATH_INFO"] == "/__identify__"
[200, {}, @app.object_id.to_s]
else
@app.call(env)
end
end
end
attr_reader :app, :port
2009-11-04 22:00:05 +00:00
def initialize(app)
@app = app
end
def host
"localhost"
2009-11-04 22:00:05 +00:00
end
def url(path)
if path =~ /^http/
path
else
(Capybara.app_host || "http://#{host}:#{port}") + path.to_s
end
2009-11-04 22:00:05 +00:00
end
def responsive?
is_running_on_port?(port)
end
2009-11-04 22:00:05 +00:00
def boot
find_available_port
2009-11-16 21:02:16 +00:00
Capybara.log "application has already booted" and return if responsive?
Capybara.log "booting Rack applicartion on port #{port}"
Timeout.timeout(10) do
Thread.new do
begin
2010-01-23 11:49:40 +00:00
require 'rack/handler/mongrel'
Rack::Handler::Mongrel.run(Identify.new(@app), :Port => port)
rescue LoadError
2010-01-23 11:49:40 +00:00
require 'rack/handler/webrick'
Rack::Handler::WEBrick.run(Identify.new(@app), :Port => port, :AccessLog => [])
end
end
Capybara.log "checking if application has booted"
loop do
Capybara.log("application has booted") and break if responsive?
sleep 0.5
2009-11-04 22:00:05 +00:00
end
end
rescue Timeout::Error
Capybara.log "Rack application timed out during boot"
exit
2009-11-04 22:00:05 +00:00
end
2009-11-07 14:35:47 +00:00
private
def find_available_port
@port = 9887
@port += 1 while is_port_open?(@port) and not is_running_on_port?(@port)
end
def is_running_on_port?(tested_port)
res = Net::HTTP.start(host, tested_port) { |http| http.get('/__identify__') }
2009-11-07 14:35:47 +00:00
if res.is_a?(Net::HTTPSuccess) or res.is_a?(Net::HTTPRedirection)
return res.body == @app.object_id.to_s
end
rescue Errno::ECONNREFUSED
return false
end
def is_port_open?(tested_port)
Timeout::timeout(1) do
begin
s = TCPSocket.new(host, tested_port)
s.close
return true
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH
return false
end
2009-11-07 14:35:47 +00:00
end
rescue Timeout::Error
2009-11-07 14:35:47 +00:00
return false
end
end