-
Notifications
You must be signed in to change notification settings - Fork 3
/
await.go
64 lines (50 loc) · 1.28 KB
/
await.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
package gormtestutil
import (
"sync"
"time"
testingi "github.com/mitchellh/go-testing-interface"
)
const (
// defaultTimeout is the default value for EnsureCompletion's config
defaultTimeout = 30 * time.Second
)
// EnsureOption allows various options to be supplied to EnsureCompletion
type EnsureOption func(*ensureConfig)
// WithTimeout is used to set a timeout for EnsureCompletion
func WithTimeout(timeout time.Duration) EnsureOption {
return func(config *ensureConfig) {
config.timeout = timeout
}
}
type ensureConfig struct {
timeout time.Duration
}
// EnsureCompletion ensures that the waitgroup completes within a specified duration or else fails
func EnsureCompletion(t testingi.T, wg *sync.WaitGroup, options ...EnsureOption) bool {
t.Helper()
if wg == nil {
t.Error("WithExpectation is nil")
return false
}
config := &ensureConfig{
timeout: defaultTimeout,
}
for _, option := range options {
option(config)
}
// Run waitgroup in goroutine
channel := make(chan struct{})
go func() {
t.Helper()
defer close(channel)
wg.Wait()
}()
// Select first response (waitgroup completion or time.After)
select {
case <-channel:
return true
case <-time.After(config.timeout):
t.Errorf("tasks did not complete within: %v", config.timeout)
return false
}
}