github.com/nilium/gitlab-runner@v12.5.0+incompatible/commands/helpers/health_check_test.go (about) 1 package helpers 2 3 import ( 4 "context" 5 "net" 6 "os" 7 "strconv" 8 "strings" 9 "testing" 10 "time" 11 12 "github.com/stretchr/testify/assert" 13 "github.com/stretchr/testify/require" 14 15 "gitlab.com/gitlab-org/gitlab-runner/helpers" 16 ) 17 18 func TestServiceWaiterCommand_NoEnvironmentVariables(t *testing.T) { 19 removeHook := helpers.MakeFatalToPanic() 20 defer removeHook() 21 22 // Make sure there are no env vars that match the pattern 23 for _, e := range os.Environ() { 24 if strings.Contains(e, "_TCP_") { 25 err := os.Unsetenv(strings.Split(e, "=")[0]) 26 require.NoError(t, err) 27 } 28 } 29 30 cmd := HealthCheckCommand{} 31 32 assert.Panics(t, func() { 33 cmd.Execute(nil) 34 }) 35 } 36 37 func TestHealthCheckCommand_Execute(t *testing.T) { 38 cases := []struct { 39 name string 40 expectedConnect bool 41 }{ 42 { 43 name: "Successful connect", 44 expectedConnect: true, 45 }, 46 { 47 name: "Unsuccessful connect because service is down", 48 expectedConnect: false, 49 }, 50 } 51 52 for _, c := range cases { 53 t.Run(c.name, func(t *testing.T) { 54 // Start listening to reverse addr 55 listener, err := net.Listen("tcp", "127.0.0.1:") 56 require.NoError(t, err) 57 58 err = os.Setenv("SERVICE_TCP_ADDR", "127.0.0.1") 59 require.NoError(t, err) 60 61 err = os.Setenv("SERVICE_TCP_PORT", strconv.Itoa(listener.Addr().(*net.TCPAddr).Port)) 62 require.NoError(t, err) 63 64 // If we don't expect to connect we close the listener. 65 if !c.expectedConnect { 66 listener.Close() 67 } 68 69 ctx, cancelFn := context.WithTimeout(context.Background(), 2*time.Second) 70 defer cancelFn() 71 done := make(chan struct{}) 72 go func() { 73 cmd := HealthCheckCommand{} 74 cmd.Execute(nil) 75 done <- struct{}{} 76 }() 77 78 select { 79 case <-ctx.Done(): 80 if c.expectedConnect { 81 require.Fail(t, "Timeout waiting to start service.") 82 } 83 case <-done: 84 if !c.expectedConnect { 85 require.Fail(t, "Expected to not connect to server") 86 } 87 } 88 }) 89 } 90 91 }