Lorenz Brun | fc5dbc6 | 2020-05-28 12:18:07 +0200 | [diff] [blame] | 1 | // Copyright 2020 The Monogon Project Authors. |
| 2 | // |
| 3 | // SPDX-License-Identifier: Apache-2.0 |
| 4 | // |
| 5 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | // you may not use this file except in compliance with the License. |
| 7 | // You may obtain a copy of the License at |
| 8 | // |
| 9 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | // |
| 11 | // Unless required by applicable law or agreed to in writing, software |
| 12 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | // See the License for the specific language governing permissions and |
| 15 | // limitations under the License. |
| 16 | |
| 17 | package e2e |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "errors" |
| 22 | "testing" |
| 23 | "time" |
| 24 | ) |
| 25 | |
| 26 | // testEventual creates a new subtest looping the given function until it either doesn't return an error anymore or |
| 27 | // the timeout is exceeded. The last returned non-context-related error is being used as the test error. |
| 28 | func testEventual(t *testing.T, name string, ctx context.Context, timeout time.Duration, f func(context.Context) error) { |
| 29 | ctx, cancel := context.WithTimeout(ctx, timeout) |
| 30 | t.Helper() |
| 31 | t.Run(name, func(t *testing.T) { |
| 32 | defer cancel() |
| 33 | var lastErr = errors.New("test didn't run to completion at least once") |
| 34 | t.Parallel() |
| 35 | for { |
| 36 | err := f(ctx) |
| 37 | if err == nil { |
| 38 | return |
| 39 | } |
| 40 | if err == ctx.Err() { |
| 41 | t.Fatal(lastErr) |
| 42 | } |
| 43 | lastErr = err |
| 44 | select { |
| 45 | case <-ctx.Done(): |
| 46 | t.Fatal(lastErr) |
| 47 | case <-time.After(1 * time.Second): |
| 48 | } |
| 49 | } |
| 50 | }) |
| 51 | } |