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" |
Serge Bazanski | 05f813b | 2023-03-16 17:58:39 +0100 | [diff] [blame] | 10 | |
| 11 | "source.monogon.dev/metropolis/test/launch" |
Mateusz Zalega | ddf19b4 | 2022-06-22 12:27:37 +0200 | [diff] [blame] | 12 | ) |
| 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. |
| 17 | func TestEventual(t *testing.T, name string, ctx context.Context, timeout time.Duration, f func(context.Context) error) { |
Serge Bazanski | 05f813b | 2023-03-16 17:58:39 +0100 | [diff] [blame] | 18 | start := time.Now() |
Mateusz Zalega | ddf19b4 | 2022-06-22 12:27:37 +0200 | [diff] [blame] | 19 | ctx, cancel := context.WithTimeout(ctx, timeout) |
| 20 | t.Helper() |
Serge Bazanski | 05f813b | 2023-03-16 17:58:39 +0100 | [diff] [blame] | 21 | launch.Log("Test: %s: starting...", name) |
Mateusz Zalega | ddf19b4 | 2022-06-22 12:27:37 +0200 | [diff] [blame] | 22 | 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 Zalega | ddf19b4 | 2022-06-22 12:27:37 +0200 | [diff] [blame] | 25 | for { |
| 26 | err := f(ctx) |
| 27 | if err == nil { |
Serge Bazanski | 05f813b | 2023-03-16 17:58:39 +0100 | [diff] [blame] | 28 | launch.Log("Test: %s: okay after %.1f seconds", name, time.Since(start).Seconds()) |
Mateusz Zalega | ddf19b4 | 2022-06-22 12:27:37 +0200 | [diff] [blame] | 29 | 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 | } |