github.com/mponton/terratest@v0.44.0/modules/ssh/ssh_test.go (about) 1 package ssh 2 3 import ( 4 "errors" 5 "fmt" 6 "testing" 7 8 grunttest "github.com/mponton/terratest/modules/testing" 9 "github.com/stretchr/testify/assert" 10 ) 11 12 func TestHostWithDefaultPort(t *testing.T) { 13 t.Parallel() 14 15 host := Host{} 16 17 assert.Equal(t, 22, host.getPort(), "host.getPort() did not return the default ssh port of 22") 18 } 19 20 func TestHostWithCustomPort(t *testing.T) { 21 t.Parallel() 22 23 customPort := 2222 24 host := Host{CustomPort: customPort} 25 26 assert.Equal(t, customPort, host.getPort(), "host.getPort() did not return the custom port number") 27 } 28 29 // global var for use in mock callback 30 var timesCalled int 31 32 func TestCheckSshConnectionWithRetryE(t *testing.T) { 33 // Reset the global call count 34 timesCalled = 0 35 36 host := Host{Hostname: "Host"} 37 retries := 10 38 39 assert.Nil(t, CheckSshConnectionWithRetryE(t, host, retries, 3, mockSshConnectionE)) 40 } 41 42 func TestCheckSshConnectionWithRetryEExceedsMaxRetries(t *testing.T) { 43 // Reset the global call count 44 timesCalled = 0 45 46 host := Host{Hostname: "Host"} 47 48 // Not enough retries 49 retries := 3 50 51 assert.Error(t, CheckSshConnectionWithRetryE(t, host, retries, 3, mockSshConnectionE)) 52 } 53 54 func TestCheckSshConnectionWithRetry(t *testing.T) { 55 // Reset the global call count 56 timesCalled = 0 57 58 host := Host{Hostname: "Host"} 59 retries := 10 60 61 CheckSshConnectionWithRetry(t, host, retries, 3, mockSshConnectionE) 62 } 63 64 func TestCheckSshCommandWithRetryE(t *testing.T) { 65 // Reset the global call count 66 timesCalled = 0 67 68 host := Host{Hostname: "Host"} 69 command := "echo -n hello world" 70 retries := 10 71 72 _, err := CheckSshCommandWithRetryE(t, host, command, retries, 3, mockSshCommandE) 73 assert.Nil(t, err) 74 } 75 76 func TestCheckSshCommandWithRetryEExceedsRetries(t *testing.T) { 77 // Reset the global call count 78 timesCalled = 0 79 80 host := Host{Hostname: "Host"} 81 command := "echo -n hello world" 82 83 // Not enough retries 84 retries := 3 85 86 _, err := CheckSshCommandWithRetryE(t, host, command, retries, 3, mockSshCommandE) 87 assert.Error(t, err) 88 } 89 90 func TestCheckSshCommandWithRetry(t *testing.T) { 91 // Reset the global call count 92 timesCalled = 0 93 94 host := Host{Hostname: "Host"} 95 command := "echo -n hello world" 96 retries := 10 97 98 CheckSshCommandWithRetry(t, host, command, retries, 3, mockSshCommandE) 99 } 100 101 func mockSshConnectionE(t grunttest.TestingT, host Host) error { 102 timesCalled += 1 103 if timesCalled >= 5 { 104 return nil 105 } else { 106 return errors.New(fmt.Sprintf("Called %v times", timesCalled)) 107 } 108 } 109 110 func mockSshCommandE(t grunttest.TestingT, host Host, command string) (string, error) { 111 return "", mockSshConnectionE(t, host) 112 }