blob: 47bf59fed789c9de59170e0a6e107734d1b41aea [file] [log] [blame]
Mateusz Zalegaddf19b42022-06-22 12:27:37 +02001// This file implements test helper functions that augment the way any given
2// test is run.
3package util
4
5import (
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.
15func 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}