Skip to content

Commit

Permalink
Merge pull request #3 from djanowski/mock-server-stop
Browse files Browse the repository at this point in the history
Add ability to stop MockServer again
  • Loading branch information
vangberg committed Jun 9, 2016
2 parents ba97239 + 7c675a0 commit 976d065
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/mock_server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,14 @@ def start
self
end

def stop
Rack::Handler::WEBrick.shutdown

wait_for_shutdown("0.0.0.0", @port)

self
end

module Methods
def mock_server(*args, &block)
app = Class.new(Sinatra::Base)
Expand All @@ -45,6 +53,7 @@ def listening?(host, port)
socket.close unless socket.nil?
true
rescue Errno::ECONNREFUSED,
Errno::ECONNRESET,
Errno::EBADF, # Windows
Errno::EADDRNOTAVAIL # Windows
false
Expand All @@ -62,4 +71,16 @@ def wait_for_service(host, port, timeout = 5)

true
end

def wait_for_shutdown(host, port, timeout = 5)
start_time = Time.now

until !listening?(host, port)
if timeout && (Time.now > (start_time + timeout))
raise SocketError.new("Socket did not close within #{timeout} seconds")
end
end

true
end
end
17 changes: 17 additions & 0 deletions test/mock_server_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,20 @@ def test_server
assert_equal "Goodbye", open("http://localhost:4002").read
end
end

class MockServerStopTest < Test::Unit::TestCase
def setup
@server = MockServer.new(HelloWorldSinatra, 4003)
@server.start
end

def test_stop_server
assert_equal "Hello", open("http://localhost:4003").read

@server.stop

assert_raises(Errno::ECONNREFUSED) {
open("http://localhost:4003").read
}
end
end

0 comments on commit 976d065

Please sign in to comment.