Skip to content

Commit

Permalink
Add Test Server Wait Helper Function (#787)
Browse files Browse the repository at this point in the history
Co-authored-by: Youngteac Hong <[email protected]>
  • Loading branch information
krapie and hackerwins authored Feb 8, 2024
1 parent 94d6e30 commit a8f6bc2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
5 changes: 4 additions & 1 deletion server/rpc/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,12 @@ func TestMain(m *testing.M) {
log.Fatal(err)
}

if err := testRPCServer.Start(); err != nil {
if err = testRPCServer.Start(); err != nil {
log.Fatalf("failed rpc listen: %s\n", err)
}
if err = helper.WaitForServerToStart(testRPCAddr); err != nil {
log.Fatal(err)
}

authInterceptor := client.NewAuthInterceptor(project.PublicKey, "")

Expand Down
32 changes: 32 additions & 0 deletions test/helper/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"context"
"fmt"
"log"
"net"
"strings"
"testing"
gotime "time"
Expand Down Expand Up @@ -454,3 +455,34 @@ func CreateDummyClientWithID(

return nil
}

// WaitForServerToStart waits for the server to start.
func WaitForServerToStart(addr string) error {
maxRetries := 10
initialDelay := 100 * gotime.Millisecond
maxDelay := 5 * gotime.Second

for attempt := 0; attempt < maxRetries; attempt++ {
// Exponential backoff calculation
delay := initialDelay * gotime.Duration(1<<uint(attempt))
fmt.Println("delay: ", delay)
if delay > maxDelay {
delay = maxDelay
}

conn, err := net.DialTimeout("tcp", addr, 1*gotime.Second)
if err != nil {
gotime.Sleep(delay)
continue
}

err = conn.Close()
if err != nil {
return fmt.Errorf("close connection: %w", err)
}

return nil
}

return fmt.Errorf("timeout for server to start: %s", addr)
}

0 comments on commit a8f6bc2

Please sign in to comment.