Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 65 lines (56 sloc) 1.226 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
require 'webrick'
require 'logger'
require 'singleton'

class WebMockServer
  include Singleton

  attr_reader :port, :started

  def host_with_port
    "localhost:#{port}"
  end

  def concurrent
    unless RUBY_PLATFORM =~ /java/
      @pid = Process.fork do
        yield
      end
    else
      Thread.new { yield }
    end
  end

  def start
    @started = true
    server = WEBrick::GenericServer.new(:Port => 0, :Logger => Logger.new("/dev/null"))
    server.logger.level = 0
    @port = server.config[:Port]

    concurrent do
      ['TERM', 'INT'].each do |signal|
        trap(signal){ server.shutdown }
      end
      server.start do |socket|
        socket.puts <<-EOT.gsub(/^\s+\|/, '')
|HTTP/1.1 200 OK\r
|Date: Fri, 31 Dec 1999 23:59:59 GMT\r
|Content-Type: text/html\r
|Content-Length: 11\r
|Set-Cookie: bar\r
|Set-Cookie: foo\r
|\r
|hello world
EOT
      end
    end


    loop do
      begin
        s = TCPSocket.new("localhost", port)
        sleep 0.1
        break
      rescue Errno::ECONNREFUSED
        sleep 0.1
      end
    end
  end

  def stop
    if @pid
      Process.kill('INT', @pid)
    end
  end
end
Something went wrong with that request. Please try again.