blob: a2b166308f91684efcc0baeb903610dad134b6aa [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"
Serge Bazanski05f813b2023-03-16 17:58:39 +010010
11 "source.monogon.dev/metropolis/test/launch"
Mateusz Zalegaddf19b42022-06-22 12:27:37 +020012)
13
14// TestEventual creates a new subtest looping the given function until it
15// either doesn't return an error anymore or the timeout is exceeded. The last
16// returned non-context-related error is being used as the test error.
17func TestEventual(t *testing.T, name string, ctx context.Context, timeout time.Duration, f func(context.Context) error) {
Serge Bazanski05f813b2023-03-16 17:58:39 +010018 start := time.Now()
Mateusz Zalegaddf19b42022-06-22 12:27:37 +020019 ctx, cancel := context.WithTimeout(ctx, timeout)
20 t.Helper()
Serge Bazanski05f813b2023-03-16 17:58:39 +010021 launch.Log("Test: %s: starting...", name)
Mateusz Zalegaddf19b42022-06-22 12:27:37 +020022 t.Run(name, func(t *testing.T) {
23 defer cancel()
24 var lastErr = errors.New("test didn't run to completion at least once")
Mateusz Zalegaddf19b42022-06-22 12:27:37 +020025 for {
26 err := f(ctx)
27 if err == nil {
Serge Bazanski05f813b2023-03-16 17:58:39 +010028 launch.Log("Test: %s: okay after %.1f seconds", name, time.Since(start).Seconds())
Mateusz Zalegaddf19b42022-06-22 12:27:37 +020029 return
30 }
31 if err == ctx.Err() {
32 t.Fatal(lastErr)
33 }
34 lastErr = err
35 select {
36 case <-ctx.Done():
37 t.Fatal(lastErr)
38 case <-time.After(1 * time.Second):
39 }
40 }
41 })
42}