-
Notifications
You must be signed in to change notification settings - Fork 40
/
runtime.go
273 lines (254 loc) · 6.66 KB
/
runtime.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Package testutils provides various utilities for use in tests.
package testutils
import (
"context"
"fmt"
"net/http"
"os"
"sync"
"syscall"
"testing"
"github.com/edaniels/golog"
"github.com/pkg/errors"
"go.uber.org/zap/zaptest/observer"
"go.viam.com/test"
"go.viam.com/utils"
)
// ContextualMainExecution reflects the execution of a main function
// that can have its lifecycle partially controlled.
type ContextualMainExecution struct {
Ready <-chan struct{}
Done <-chan error
Start func()
Stop func()
QuitSignal func(t *testing.T) // reflects syscall.SIGQUIT
ExpectIters func(t *testing.T, amount int) // expect a certain amount of iters
WaitIters func(t *testing.T) // waits for iters defined by ExpectIters
}
// ContextualMain calls a main entry point function with a cancellable
// context via the returned execution struct. The main function is run
// in a separate goroutine.
func ContextualMain(
main func(ctx context.Context, args []string, logger golog.Logger) error,
args []string,
logger golog.Logger,
) ContextualMainExecution {
return contextualMain(main, args, logger)
}
func contextualMain(
main func(ctx context.Context, args []string, logger golog.Logger) error,
args []string,
logger golog.Logger,
) ContextualMainExecution {
ctx, stop := context.WithCancel(context.Background())
quitC := make(chan os.Signal)
ctx = utils.ContextWithQuitSignal(ctx, quitC)
readyC := make(chan struct{}, 1)
ctx = utils.ContextWithReadyFunc(ctx, readyC)
readyF := utils.ContextMainReadyFunc(ctx)
iterC := make(chan struct{})
ctx = utils.ContextWithIterFunc(ctx, func() {
iterC <- struct{}{}
})
doneC := make(chan error, 1)
mainDone := make(chan struct{})
var err error
var startOnce sync.Once
start := func() {
startOnce.Do(func() {
utils.PanicCapturingGo(func() {
// if main is not a daemon like function or does not error out, just be "ready"
// after execution is complete.
defer readyF()
defer close(mainDone)
err = main(ctx, append([]string{"main"}, args...), logger)
doneC <- err
})
})
}
earlyDone := func(t *testing.T) {
t.Helper()
if err != nil { // safe to check as we synchronize on mainDone
fatalf(t, "main function completed while waiting with error: %v", err)
} else {
fatal(t, "main function completed while waiting")
}
}
var waitIters chan struct{}
var expectMu sync.Mutex
closeDiscard := make(chan struct{})
discardClosed := make(chan struct{})
discardIter := func() {
defer close(discardClosed)
for {
select {
case <-closeDiscard:
return
default:
}
select {
case <-closeDiscard:
case <-mainDone:
return
case <-iterC:
}
}
}
utils.PanicCapturingGo(discardIter)
return ContextualMainExecution{
Ready: readyC,
Done: doneC,
Start: start,
Stop: stop,
QuitSignal: func(t *testing.T) {
t.Helper()
select {
case <-mainDone:
earlyDone(t)
return
case quitC <- syscall.SIGQUIT:
}
},
ExpectIters: func(t *testing.T, amount int) {
t.Helper()
expectMu.Lock()
started := make(chan struct{})
close(closeDiscard)
<-discardClosed
utils.PanicCapturingGo(func() {
defer expectMu.Unlock()
waitIters = make(chan struct{})
totalIters := 0
expectingIters := amount
close(started)
for {
select {
case <-mainDone:
earlyDone(t)
return
case <-iterC:
totalIters++
}
if totalIters < expectingIters {
continue
}
close(waitIters)
// swap to discard
closeDiscard = make(chan struct{})
discardClosed = make(chan struct{})
utils.PanicCapturingGo(discardIter)
return
}
})
<-started
},
WaitIters: func(t *testing.T) {
t.Helper()
<-waitIters
},
}
}
// MainTestCase describes how to execute a main function and what
// to expect from it.
type MainTestCase struct {
Name string
Args []string
Err string
Before func(t *testing.T, logger golog.Logger, exec *ContextualMainExecution)
During func(ctx context.Context, t *testing.T, exec *ContextualMainExecution)
After func(t *testing.T, logs *observer.ObservedLogs)
}
var (
completedBeforeExpected = "main function completed before expected"
errCompletedBeforeExpected = errors.New(completedBeforeExpected)
)
// TestMain tests a main function with a series of test cases in serial.
func TestMain(t *testing.T, mainWithArgs func(ctx context.Context, args []string, logger golog.Logger) error, tcs []MainTestCase) {
for i, tc := range tcs {
testCaseName := tc.Name
if testCaseName == "" {
testCaseName = fmt.Sprintf("%d", i)
}
t.Run(testCaseName, func(t *testing.T) {
logger, logs := golog.NewObservedTestLogger(t)
exec := ContextualMain(mainWithArgs, tc.Args, logger)
if tc.Before != nil {
tc.Before(t, logger, &exec)
}
exec.Start()
<-exec.Ready
done := make(chan error)
var waitingInDuring bool
var waitingInDuringFailed bool
var waitMu sync.Mutex
if tc.During != nil {
waitingInDuring = true
}
cancelCtx, cancel := context.WithCancel(context.Background())
defer cancel()
var doneErr error
utils.PanicCapturingGo(func() {
err := utils.FilterOutError(<-exec.Done, context.Canceled)
doneErr = err
waitMu.Lock()
if waitingInDuring {
waitingInDuringFailed = true
cancel()
if err == nil {
tError(t, errCompletedBeforeExpected)
} else {
tError(t, errors.Wrapf(doneErr, "%s with error", completedBeforeExpected))
}
}
waitMu.Unlock()
done <- err
})
if tc.During != nil {
tc.During(cancelCtx, t, &exec)
waitMu.Lock()
if waitingInDuringFailed {
// covers the case where the writer of During does not
// error themselves.
defer waitMu.Unlock()
err := <-done
if err == nil {
fatal(t, errCompletedBeforeExpected)
} else {
fatal(t, errors.Wrapf(doneErr, "%s with error", completedBeforeExpected))
}
return
}
waitingInDuring = false
waitMu.Unlock()
}
exec.Stop()
err := <-done
if tc.Err == "" {
test.That(t, err, test.ShouldBeNil)
} else {
test.That(t, err, test.ShouldNotBeNil)
test.That(t, err.Error(), test.ShouldContainSubstring, tc.Err)
}
if tc.After != nil {
tc.After(t, logs)
}
})
}
}
func fatalf(t *testing.T, format string, args ...interface{}) {
t.Helper()
fatal(t, fmt.Sprintf(format, args...))
}
var tError = func(t *testing.T, args ...interface{}) {
t.Helper()
t.Error(args...)
}
var fatal = func(t *testing.T, args ...interface{}) {
t.Helper()
t.Fatal(args...)
}
// Teardown cleans up any temporary resources used by tests.
func Teardown() {
teardownMongoDB()
http.DefaultClient.CloseIdleConnections()
}