# encoding: utf-8 require 'sinatra/base' require 'socket' class WatirSpec::Server < ::Sinatra::Base class << self attr_accessor :autorun def run_async case RUBY_PLATFORM when /java/ Thread.new { run! } sleep 0.1 until WatirSpec::Server.running? when /windows/ run_in_child_process sleep 0.5 until listening? else pid = fork { run! } sleep 0.5 until listening? end if pid # is this really necessary? at_exit { begin Process.kill 0, pid alive = true rescue Errno::ESRCH alive = false end Process.kill(9, pid) if alive } end end def run! handler = detect_rack_handler handler.run(self, :Host => bind, :Port => port) { @running = true } end def listening? $stderr.puts "trying #{bind}:#{port}..." TCPSocket.new(bind, port).close true rescue false end def find_free_port_above(int) port = int until free_port?(port) port += 1 end port end def autorun @autorun ||= true end def should_run? autorun && !running? end def running? defined?(@running) && @running end SOCKET_ERRORS = [Errno::EADDRINUSE] SOCKET_ERRORS << SocketError if defined?(SocketError) # ruby versions... def free_port?(port) s = TCPServer.new(@host, port) s.close true rescue *SOCKET_ERRORS false end private def run_in_child_process begin require 'childprocess' rescue LoadError => ex raise "please run `gem install childprocess` for WatirSpec on Windows + MRI\n\t(caught: #{ex.message})" end path = File.expand_path('../../spec_helper.rb', __FILE__) process = ChildProcess.build(WatirSpec.ruby, path) process.io.inherit! if $DEBUG process.start at_exit { process.stop } end end set :app_file, __FILE__ set :root, File.dirname(__FILE__) set :public_folder, File.join(root, 'fixtures') set :static, true set :run, false set :environment, :production set :bind, 'localhost'# if Config::CONFIG['host_os'] =~ /windows/ set :port, find_free_port_above(2000) get '/' do self.class.name end get '/big' do Class.new do def each(&blk) yield "