| 36 | } |
| 37 | |
| 38 | func (f *flaky) Run(fn func(t testing.TB)) { |
| 39 | var last error |
| 40 | |
| 41 | for attempt := 1; attempt <= f.o.MaxAttempts; attempt++ { |
| 42 | r := &recorder{ |
| 43 | TB: f.t, |
| 44 | fail: func(s string) { last = errors.New(s) }, |
| 45 | fatal: func(s string) { last = errors.New(s) }, |
| 46 | } |
| 47 | |
| 48 | func() { |
| 49 | failCodes := []int{RecorderFailNow, RecorderFatalf, RecorderFatal} |
| 50 | defer func() { |
| 51 | if rec := recover(); rec != nil { |
| 52 | if code, ok := rec.(int); ok && !slices.Contains(failCodes, code) { |
| 53 | panic(rec) |
| 54 | } |
| 55 | } |
| 56 | }() |
| 57 | |
| 58 | fn(r) |
| 59 | }() |
| 60 | |
| 61 | if !r.Failed() { |
| 62 | return |
| 63 | } |
| 64 | |
| 65 | if attempt < f.o.MaxAttempts { |
| 66 | backoff := f.o.InitialBackoff * time.Duration(1<<uint(attempt-1)) |
| 67 | time.Sleep(applyJitter(backoff, f.o.Jitter)) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | f.t.Fatalf("[%s] test failed after %d attempts: %v", f.t.Name(), f.o.MaxAttempts, last) |
| 72 | } |
| 73 | |
| 74 | func applyJitter(d time.Duration, jitter float64) time.Duration { |
| 75 | if jitter == 0 { |