From 51e32256a6401f9cb3f6cda040a1144d1ac37caf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20M=C3=BCller?= Date: Tue, 18 Dec 2018 01:29:18 +0100 Subject: [PATCH] Add run_server helper --- spec/std/http/server/server_spec.cr | 45 +++++++++++++++++++++++------ 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/spec/std/http/server/server_spec.cr b/spec/std/http/server/server_spec.cr index be4b3f9ae11b..34f449bb03c6 100644 --- a/spec/std/http/server/server_spec.cr +++ b/spec/std/http/server/server_spec.cr @@ -107,6 +107,32 @@ private def run_server(server) end end +# Helper method which runs *server* +# 1. Spawns `server.listen` in a new fiber. +# 2. Waits until `server.listening?`. +# 3. Yields to the given block. +# 4. Ensures the server is closed. +# 5. After returning from the block, it waits for the server to gracefully +# shut down before continuing execution in the current fiber. +private def run_server(server) + server_done = Channel(Nil).new + + spawn do + server.listen + ensure + server_done.send nil + end + + begin + wait_for { server.listening? } + + yield server_done + ensure + server.close unless server.closed? + server_done.receive + end +end + module HTTP class Server describe Response do @@ -269,10 +295,14 @@ module HTTP address = server.bind_unused_port address.port.should_not eq(0) + server.close + server = Server.new { |ctx| } port = server.bind_tcp(0).port port.should_not eq(0) + ensure + server.close if server ensure_no_ports_leaking end @@ -395,6 +425,8 @@ module HTTP server.bind tcp_server server.addresses.should eq addresses + ensure + server.try &.close ensure_no_ports_leaking end @@ -599,18 +631,13 @@ module HTTP server.bind socket1 socket2 = server.bind_unix path2 - spawn server.listen - wait_for { server.listening? } - - unix_request(path1).should eq "Test Server (#{path1})" - unix_request(path2).should eq "Test Server (#{path2})" - - server.close + run_server(server) do + unix_request(path1).should eq "Test Server (#{path1})" + unix_request(path2).should eq "Test Server (#{path2})" + end File.exists?(path1).should be_false File.exists?(path2).should be_false - - ensure_no_ports_leaking ensure File.delete(path1) if File.exists?(path1) File.delete(path2) if File.exists?(path2)