summaryrefslogtreecommitdiff
path: root/test/webrick/test_server.rb
blob: eab7a5ca5fa087d60a5ddab301edd7c2a66a2107 (plain)
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
require "test/unit"
require "tempfile"
require "webrick"
require File.join(File.dirname(__FILE__), "utils.rb")

class TestWEBrickServer < Test::Unit::TestCase
  class Echo < WEBrick::GenericServer
    def run(sock)
      while line = sock.gets
        sock << line
      end
    end
  end

  def test_server
    TestWEBrick.start_server(Echo){|server, addr, port, log|
      TCPSocket.open(addr, port){|sock|
        sock.puts("foo"); assert_equal("foo\n", sock.gets, log.call)
        sock.puts("bar"); assert_equal("bar\n", sock.gets, log.call)
        sock.puts("baz"); assert_equal("baz\n", sock.gets, log.call)
        sock.puts("qux"); assert_equal("qux\n", sock.gets, log.call)
      }
    }
  end

  def test_callbacks
    accepted = started = stopped = 0
    config = {
      :AcceptCallback => Proc.new{ accepted += 1 },
      :StartCallback => Proc.new{ started += 1 },
      :StopCallback => Proc.new{ stopped += 1 },
    }
    TestWEBrick.start_server(Echo, config){|server, addr, port, log|
      true while server.status != :Running
      assert_equal(started, 1, log.call)
      assert_equal(stopped, 0, log.call)
      assert_equal(accepted, 0, log.call)
      TCPSocket.open(addr, port){|sock| (sock << "foo\n").gets }
      TCPSocket.open(addr, port){|sock| (sock << "foo\n").gets }
      TCPSocket.open(addr, port){|sock| (sock << "foo\n").gets }
      assert_equal(accepted, 3, log.call)
    }
    assert_equal(started, 1)
    assert_equal(stopped, 1)
  end

  def test_daemon
    begin
      pid = Process.fork{
        WEBrick::Daemon.start
        sleep
      }
      assert(Process.kill(:KILL, pid))
    rescue NotImplementedError
      # snip this test
    end
  end
end