Skip to content

Commit

Permalink
HTTP/SMTP: Waiting for port to become connectable before continuing t…
Browse files Browse the repository at this point in the history
…est run
  • Loading branch information
Lucas Hinderberger committed Jul 4, 2024
1 parent 359c088 commit 822e78f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions http_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -78,6 +79,8 @@ func (ats *Suite) StartHttpServer() {
run()
} else {
go run()

util.WaitForTCP(ats.HttpServer.Addr)
}
}

Expand Down
23 changes: 23 additions & 0 deletions pkg/lib/util/net.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
3 changes: 3 additions & 0 deletions smtp_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down

0 comments on commit 822e78f

Please sign in to comment.