Mateusz Zalega | ddf19b4 | 2022-06-22 12:27:37 +0200 | [diff] [blame] | 1 | // This file implements test helper functions that augment the way any given |
| 2 | // test is run. |
| 3 | package util |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "errors" |
| 8 | "testing" |
| 9 | "time" |
| 10 | ) |
| 11 | |
| 12 | // TestEventual creates a new subtest looping the given function until it |
| 13 | // either doesn't return an error anymore or the timeout is exceeded. The last |
| 14 | // returned non-context-related error is being used as the test error. |
| 15 | func TestEventual(t *testing.T, name string, ctx context.Context, timeout time.Duration, f func(context.Context) error) { |
| 16 | ctx, cancel := context.WithTimeout(ctx, timeout) |
| 17 | t.Helper() |
| 18 | t.Run(name, func(t *testing.T) { |
| 19 | defer cancel() |
| 20 | var lastErr = errors.New("test didn't run to completion at least once") |
| 21 | t.Parallel() |
| 22 | for { |
| 23 | err := f(ctx) |
| 24 | if err == nil { |
| 25 | return |
| 26 | } |
| 27 | if err == ctx.Err() { |
| 28 | t.Fatal(lastErr) |
| 29 | } |
| 30 | lastErr = err |
| 31 | select { |
| 32 | case <-ctx.Done(): |
| 33 | t.Fatal(lastErr) |
| 34 | case <-time.After(1 * time.Second): |
| 35 | } |
| 36 | } |
| 37 | }) |
| 38 | } |