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

116 lines
2.3 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'
2010-07-09 18:30:50 +00:00
require 'capybara/timeout'
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
2010-02-19 17:13:03 +00:00
def handler
begin
require 'rack/handler/thin'
Rack::Handler::Thin
rescue LoadError
begin
require 'rack/handler/mongrel'
Rack::Handler::Mongrel
rescue LoadError
require 'rack/handler/webrick'
Rack::Handler::WEBrick
end
end
end
2009-11-04 22:00:05 +00:00
def boot
return self unless @app
find_available_port
Capybara.log "application has already booted" and return self if responsive?
2009-11-16 21:02:16 +00:00
Capybara.log "booting Rack applicartion on port #{port}"
2010-02-26 08:04:45 +00:00
Thread.new do
handler.run(Identify.new(@app), :Port => port, :AccessLog => [])
end
Capybara.log "checking if application has booted"
2010-07-09 18:30:50 +00:00
Capybara.timeout(10) do
2010-02-26 08:04:45 +00:00
if responsive?
Capybara.log("application has booted")
true
else
sleep 0.5
2010-02-26 08:04:45 +00:00
false
2009-11-04 22:00:05 +00:00
end
end
self
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
2010-03-24 17:21:33 +00:00
rescue Errno::ECONNREFUSED, Errno::EBADF
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
end
rescue Timeout::Error
return false
end
2009-11-07 14:35:47 +00:00
end