/
eventually.go
83 lines (69 loc) · 1.68 KB
/
eventually.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Copyright (c) 2018 Yandex LLC. All rights reserved.
// Author: Maxim Kolganov <manykey@yandex-team.ru>
package testutil
import (
"context"
"time"
testing "github.com/mitchellh/go-testing-interface"
)
func Eventually(t testing.T, check CheckFunc, opts ...EventuallyOption) bool {
options := &eventuallyOptions{
timeout: 5 * time.Second,
pollInterval: 10 * time.Millisecond,
}
for _, opt := range opts {
opt(options)
}
ctx, cancel := context.WithTimeout(context.Background(), options.timeout)
defer cancel()
success := make(chan struct{})
// check could block, so it should be done in a separate goroutine.
go func() {
ticker := time.NewTicker(options.pollInterval)
defer ticker.Stop()
for {
ok := check()
if ok {
close(success)
return
}
select {
case <-ctx.Done():
return
case <-ticker.C:
continue
}
}
}()
select {
case <-ctx.Done():
t.Fatalf("Eventually condition not met: "+options.messageFormat, options.formatArgs...)
return false
case <-success:
return true
}
}
type eventuallyOptions struct {
timeout time.Duration
pollInterval time.Duration
messageFormat string
formatArgs []interface{}
}
func PollTimeout(timeout time.Duration) EventuallyOption {
return func(opts *eventuallyOptions) {
opts.timeout = timeout
}
}
func PollInterval(interval time.Duration) EventuallyOption {
return func(opts *eventuallyOptions) {
opts.pollInterval = interval
}
}
type CheckFunc func() bool
type EventuallyOption func(opts *eventuallyOptions)
func Message(format string, args ...interface{}) EventuallyOption {
return func(opts *eventuallyOptions) {
opts.messageFormat = format
opts.formatArgs = args
}
}