diff --git a/http_server.go b/http_server.go index c17844e..f4a4411 100644 --- a/http_server.go +++ b/http_server.go @@ -13,6 +13,7 @@ import ( "github.com/pkg/errors" "github.com/programmfabrik/apitest/internal/httpproxy" + "github.com/programmfabrik/apitest/pkg/lib/util" "github.com/programmfabrik/golib" "github.com/sirupsen/logrus" ) @@ -78,6 +79,8 @@ func (ats *Suite) StartHttpServer() { run() } else { go run() + + util.WaitForTCP(ats.HttpServer.Addr) } } diff --git a/pkg/lib/util/net.go b/pkg/lib/util/net.go new file mode 100644 index 0000000..845b05c --- /dev/null +++ b/pkg/lib/util/net.go @@ -0,0 +1,23 @@ +package util + +import ( + "net" + "time" + + "github.com/sirupsen/logrus" +) + +// WaitForTCP polls indefinitely until it can connect to the given TCP address. +func WaitForTCP(addr string) { + logrus.Infof("Waiting for TCP address %q to become connectable...", addr) + + for { + c, err := net.Dial("tcp", addr) + if err == nil { + c.Close() + break + } + + time.Sleep(10 * time.Millisecond) + } +} diff --git a/smtp_server.go b/smtp_server.go index 53ba793..bfb36aa 100644 --- a/smtp_server.go +++ b/smtp_server.go @@ -8,6 +8,7 @@ import ( "github.com/sirupsen/logrus" "github.com/programmfabrik/apitest/internal/smtp" + "github.com/programmfabrik/apitest/pkg/lib/util" ) // StartSmtpServer starts the testing SMTP server, if configured. @@ -29,6 +30,8 @@ func (ats *Suite) StartSmtpServer() { logrus.Fatal("SMTP server ListenAndServe:", err) } }() + + util.WaitForTCP(ats.SmtpServer.Addr) } // StopSmtpServer stops the SMTP server that was started using StartSMTPServer.