Skip to content

Commit

Permalink
test/example: Fix flakiness
Browse files Browse the repository at this point in the history
The example test is flaky because `go ListenAndServe()`
is not always ready to accept connections by the time
we get to making the request.

To fix this, start a listener explicitly in a blocking manner,
and run the Serve goroutine separately.
  • Loading branch information
abhinav committed Oct 11, 2022
1 parent ed22a6b commit 3734d3c
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ package fx_test
import (
"context"
"log"
"net"
"net/http"
"os"
"time"
Expand Down Expand Up @@ -145,9 +146,11 @@ func NewMux(lc fx.Lifecycle, logger *log.Logger) *http.ServeMux {
// passed via Go's usual context.Context.
OnStart: func(context.Context) error {
logger.Print("Starting HTTP server.")
// In production, we'd want to separate the Listen and Serve phases for
// better error-handling.
go server.ListenAndServe()
ln, err := net.Listen("tcp", server.Addr)
if err != nil {
return err
}
go server.Serve(ln)
return nil
},
OnStop: func(ctx context.Context) error {
Expand Down

0 comments on commit 3734d3c

Please sign in to comment.