2021-09-11 21:49:46 +00:00
|
|
|
package healthcheck
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"errors"
|
|
|
|
|
"testing"
|
2021-09-11 22:22:55 +00:00
|
|
|
"time"
|
2021-09-11 21:49:46 +00:00
|
|
|
|
|
|
|
|
"github.com/golang/mock/gomock"
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func Test_healthCheck(t *testing.T) {
|
|
|
|
|
t.Parallel()
|
|
|
|
|
|
|
|
|
|
canceledCtx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
cancel()
|
|
|
|
|
|
|
|
|
|
someErr := errors.New("error")
|
|
|
|
|
|
|
|
|
|
testCases := map[string]struct {
|
|
|
|
|
ctx context.Context
|
|
|
|
|
runErr error
|
|
|
|
|
stopCall bool
|
|
|
|
|
err error
|
|
|
|
|
}{
|
|
|
|
|
"success": {
|
|
|
|
|
ctx: context.Background(),
|
|
|
|
|
},
|
|
|
|
|
"error": {
|
|
|
|
|
ctx: context.Background(),
|
|
|
|
|
runErr: someErr,
|
|
|
|
|
err: someErr,
|
|
|
|
|
},
|
|
|
|
|
"context canceled": {
|
|
|
|
|
ctx: canceledCtx,
|
|
|
|
|
stopCall: true,
|
|
|
|
|
err: context.Canceled,
|
|
|
|
|
},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
for name, testCase := range testCases {
|
|
|
|
|
testCase := testCase
|
|
|
|
|
t.Run(name, func(t *testing.T) {
|
|
|
|
|
t.Parallel()
|
|
|
|
|
ctrl := gomock.NewController(t)
|
|
|
|
|
|
|
|
|
|
stopped := make(chan struct{})
|
|
|
|
|
|
|
|
|
|
pinger := NewMockPinger(ctrl)
|
|
|
|
|
pinger.EXPECT().Run().DoAndReturn(func() error {
|
|
|
|
|
if testCase.stopCall {
|
|
|
|
|
<-stopped
|
|
|
|
|
}
|
|
|
|
|
return testCase.runErr
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
if testCase.stopCall {
|
|
|
|
|
pinger.EXPECT().Stop().DoAndReturn(func() {
|
|
|
|
|
close(stopped)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
err := healthCheck(testCase.ctx, pinger)
|
|
|
|
|
|
|
|
|
|
assert.ErrorIs(t, testCase.err, err)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
t.Run("canceled real pinger", func(t *testing.T) {
|
|
|
|
|
t.Parallel()
|
|
|
|
|
|
2021-09-11 22:22:55 +00:00
|
|
|
pinger := newPinger("1.1.1.1")
|
2021-09-11 21:49:46 +00:00
|
|
|
|
|
|
|
|
canceledCtx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
cancel()
|
|
|
|
|
|
|
|
|
|
err := healthCheck(canceledCtx, pinger)
|
|
|
|
|
|
|
|
|
|
assert.ErrorIs(t, context.Canceled, err)
|
|
|
|
|
})
|
2021-09-11 22:22:55 +00:00
|
|
|
|
|
|
|
|
t.Run("ping 127.0.0.1", func(t *testing.T) {
|
|
|
|
|
t.Parallel()
|
|
|
|
|
|
|
|
|
|
pinger := newPinger("127.0.0.1")
|
|
|
|
|
|
|
|
|
|
const timeout = 100 * time.Millisecond
|
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
|
|
err := healthCheck(ctx, pinger)
|
|
|
|
|
|
|
|
|
|
assert.NoError(t, err)
|
|
|
|
|
})
|
2021-09-11 21:49:46 +00:00
|
|
|
}
|