forked from kyma-project/kyma
/
repeat.go
45 lines (36 loc) · 882 Bytes
/
repeat.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package repeat
import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func RequireFuncAtMost(t *testing.T, fn func() error, duration time.Duration) {
t.Helper()
require.NoError(t, FuncAtMost(fn, duration))
}
func AssertFuncAtMost(t *testing.T, fn func() error, duration time.Duration) {
t.Helper()
assert.NoError(t, FuncAtMost(fn, duration))
}
func FuncAtMost(fn func() error, duration time.Duration) error {
var (
tick = time.Tick(time.Second)
timeout = time.After(duration)
lastErr error
execCnt uint
)
for {
select {
case <-timeout:
return fmt.Errorf("waiting for function failed in given timeout %v. Function was executed %d times. Last error: %v", duration, execCnt, lastErr)
case <-tick:
execCnt++
if lastErr = fn(); lastErr != nil {
continue
}
return nil
}
}
}