Eventually is like require.Eventually except it allows passing a context into the condition. It is safe to use with `require.*`. If ctx times out, the test will fail, but not immediately. It is the caller's responsibility to exit early if required. It is the caller's responsibility to ensure that
(ctx context.Context, t testing.TB, condition func(ctx context.Context) (done bool), tick time.Duration, msgAndArgs ...interface{})
| 22 | // condition is not run in a goroutine; use the provided |
| 23 | // context argument for cancellation if required. |
| 24 | func Eventually(ctx context.Context, t testing.TB, condition func(ctx context.Context) (done bool), tick time.Duration, msgAndArgs ...interface{}) (done bool) { |
| 25 | t.Helper() |
| 26 | |
| 27 | if _, ok := ctx.Deadline(); !ok { |
| 28 | panic("developer error: must set deadline or timeout on ctx") |
| 29 | } |
| 30 | |
| 31 | msg := "Eventually timed out" |
| 32 | if len(msgAndArgs) > 0 { |
| 33 | m, ok := msgAndArgs[0].(string) |
| 34 | if !ok { |
| 35 | panic("developer error: first argument of msgAndArgs must be a string") |
| 36 | } |
| 37 | msg = fmt.Sprintf(m, msgAndArgs[1:]...) |
| 38 | } |
| 39 | |
| 40 | ticker := time.NewTicker(tick) |
| 41 | defer ticker.Stop() |
| 42 | for tick := ticker.C; ; { |
| 43 | select { |
| 44 | case <-ctx.Done(): |
| 45 | assert.NoError(t, ctx.Err(), msg) |
| 46 | return false |
| 47 | case <-tick: |
| 48 | if !assert.NoError(t, ctx.Err(), msg) { |
| 49 | return false |
| 50 | } |
| 51 | if condition(ctx) { |
| 52 | return true |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | } |