diff --git a/FitNesseRoot/HttpTestSuite/SuiteSetUp/content.txt b/FitNesseRoot/HttpTestSuite/SuiteSetUp/content.txt index 5f32d9e..c7af8b7 100644 --- a/FitNesseRoot/HttpTestSuite/SuiteSetUp/content.txt +++ b/FitNesseRoot/HttpTestSuite/SuiteSetUp/content.txt @@ -3,3 +3,4 @@ |set port |5000 | |set directory |${PUBLIC_DIR} | |start server | +|ensure |server is started within |PT10S| diff --git a/src/main/java/Server.java b/src/main/java/Server.java index 1cc846a..1a885d6 100644 --- a/src/main/java/Server.java +++ b/src/main/java/Server.java @@ -1,3 +1,10 @@ +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.UnknownHostException; +import java.time.Duration; +import java.time.LocalTime; + public class Server { private String startCommand; private String directory; @@ -19,10 +26,29 @@ public void setPort(String port) { public void startServer() throws Exception { String command = startCommand + " -p " + port + " -d " + directory; process = Runtime.getRuntime().exec(command); - Thread.sleep(2000); } - public void stopServer() throws Exception { + public boolean serverIsStartedWithin(String timeout) { + LocalTime abortTime = LocalTime.now().plus(Duration.parse(timeout)); + while (LocalTime.now().isBefore(abortTime)) { + if (isServerListeningOn(Integer.parseInt(this.port))) + return true; + } + return false; + } + + private boolean isServerListeningOn(int port) { + try (Socket socket = new Socket()) { + socket.connect(new InetSocketAddress("localhost", port), 1000); + return true; + } catch (UnknownHostException e) { + throw new IllegalArgumentException(e); + } catch (IOException e) { + return false; + } + } + + public void stopServer() { process.destroy(); } }