forked from irinazheltisheva/powergate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflaky.go
More file actions
65 lines (55 loc) · 1.18 KB
/
flaky.go
File metadata and controls
65 lines (55 loc) · 1.18 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package tests
import (
"runtime"
"sync"
"testing"
"github.com/stretchr/testify/require"
)
// FlakyT provides retry mechanisms to test.
type FlakyT struct {
t *testing.T
failed bool
cls []func()
}
// NewFlakyT creates a new FlakyT.
func NewFlakyT(t *testing.T) *FlakyT {
return &FlakyT{
t: t,
}
}
var _ require.TestingT = (*FlakyT)(nil)
// Errorf registers an error message.
func (ft *FlakyT) Errorf(format string, args ...interface{}) {
ft.t.Logf(format, args...)
}
// FailNow indicates to fail the test.
func (ft *FlakyT) FailNow() {
ft.failed = true
runtime.Goexit()
}
// Cleanup registers a cleanup function.
func (ft *FlakyT) Cleanup(cls func()) {
ft.cls = append([]func(){cls}, ft.cls...)
}
var numRetries = 5
// RunFlaky runs a flaky test with retries.
func RunFlaky(t *testing.T, f func(ft *FlakyT)) {
for i := 0; i < numRetries; i++ {
var wg sync.WaitGroup
wg.Add(1)
ft := NewFlakyT(t)
go func() {
defer wg.Done()
f(ft)
}()
wg.Wait()
for _, f := range ft.cls {
f()
}
if !ft.failed {
return
}
ft.t.Logf("test %s attempt %d/%d failed, retrying...", t.Name(), i+1, numRetries)
}
t.Fatalf("test failed after %d retries", numRetries)
}