github.com/filecoin-project/bacalhau@v0.3.23-0.20230228154132-45c989550ace/pkg/publicapi/util_test.go (about) 1 package publicapi 2 3 import ( 4 "context" 5 "fmt" 6 "testing" 7 "time" 8 9 "github.com/filecoin-project/bacalhau/pkg/libp2p" 10 "github.com/filecoin-project/bacalhau/pkg/system" 11 "github.com/phayes/freeport" 12 "github.com/stretchr/testify/require" 13 ) 14 15 const TimeToWaitForServerReply = 10 16 const TimeToWaitForHealthy = 50 17 18 //nolint:unused // used in tests 19 func setupNodeForTest(t *testing.T, cm *system.CleanupManager) *APIClient { 20 // blank config should result in using defaults in node.Node constructor 21 return setupNodeForTestWithConfig(t, cm, APIServerConfig{}) 22 } 23 24 //nolint:unused // used in tests 25 func setupNodeForTestWithConfig(t *testing.T, cm *system.CleanupManager, serverConfig APIServerConfig) *APIClient { 26 require.NoError(t, system.InitConfigForTesting(t)) 27 ctx := context.Background() 28 29 libp2pPort, err := freeport.GetFreePort() 30 require.NoError(t, err) 31 32 apiPort, err := freeport.GetFreePort() 33 require.NoError(t, err) 34 35 libp2pHost, err := libp2p.NewHost(libp2pPort) 36 require.NoError(t, err) 37 38 apiServer, err := NewAPIServer(APIServerParams{ 39 Host: libp2pHost, 40 Address: "0.0.0.0", 41 Port: apiPort, 42 Config: serverConfig, 43 }) 44 require.NoError(t, err) 45 46 go func() { 47 err := apiServer.ListenAndServe(ctx, cm) 48 require.NoError(t, err) 49 }() 50 51 client := NewAPIClient(apiServer.GetURI()) 52 require.NoError(t, waitForHealthy(ctx, client)) 53 return client 54 } 55 56 //nolint:unused // used in tests 57 func waitForHealthy(ctx context.Context, c *APIClient) error { 58 ch := make(chan bool) 59 go func() { 60 for { 61 alive, err := c.Alive(ctx) 62 if err == nil && alive { 63 ch <- true 64 return 65 } 66 67 time.Sleep(time.Duration(TimeToWaitForHealthy) * time.Millisecond) 68 } 69 }() 70 71 select { 72 case <-ch: 73 return nil 74 case <-time.After(time.Duration(TimeToWaitForServerReply) * time.Second): 75 return fmt.Errorf("server did not reply after %ss", time.Duration(TimeToWaitForServerReply)*time.Second) 76 } 77 }