generated from golang-templates/seed
-
Notifications
You must be signed in to change notification settings - Fork 29
/
a.go
334 lines (300 loc) · 8.16 KB
/
a.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
package goyek
import (
"context"
"io"
"io/ioutil"
"os"
"runtime"
"runtime/debug"
"strings"
"sync"
"unicode"
"unicode/utf8"
)
// A is a type passed to [Task.Action] functions to manage task state
// and support formatted task logs.
//
// A task ends when its action function returns or calls any of the methods
// FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf.
// Those methods must be called only from the goroutine running the action function.
//
// The other reporting methods, such as the variations of Log and Error,
// may be called simultaneously from multiple goroutines.
type A struct {
ctx context.Context
name string
output io.Writer
logger Logger
mu sync.Mutex
failed bool
skipped bool
cleanups []func()
}
// Context returns the run context.
func (a *A) Context() context.Context {
return a.ctx
}
// Name returns the name of the running task.
func (a *A) Name() string {
return a.name
}
// Output returns the destination used for printing messages.
func (a *A) Output() io.Writer {
return a.output
}
// Log formats its arguments using default formatting, analogous to Println,
// and writes the text to [A.Output]. A final newline is added.
func (a *A) Log(args ...interface{}) {
a.logger.Log(a.output, args...)
}
// Logf formats its arguments according to the format, analogous to Printf,
// and writes the text to [A.Output]. A final newline is added.
func (a *A) Logf(format string, args ...interface{}) {
a.logger.Logf(a.output, format, args...)
}
// Error is equivalent to [A.Log] followed by [A.Fail].
func (a *A) Error(args ...interface{}) {
if l, ok := a.logger.(interface {
Error(w io.Writer, args ...interface{})
}); ok {
l.Error(a.output, args...)
} else {
a.logger.Log(a.output, args...)
}
a.Fail()
}
// Errorf is equivalent to [A.Logf] followed by [A.Fail].
func (a *A) Errorf(format string, args ...interface{}) {
if l, ok := a.logger.(interface {
Errorf(w io.Writer, format string, args ...interface{})
}); ok {
l.Errorf(a.output, format, args...)
} else {
a.logger.Logf(a.output, format, args...)
}
a.Fail()
}
// Failed reports whether the function has failed.
func (a *A) Failed() bool {
a.mu.Lock()
res := a.failed
a.mu.Unlock()
return res
}
// Fail marks the function as having failed but continues execution.
func (a *A) Fail() {
a.mu.Lock()
a.failed = true
a.mu.Unlock()
}
// Fatal is equivalent to [A.Log] followed by [A.FailNow].
func (a *A) Fatal(args ...interface{}) {
if l, ok := a.logger.(interface {
Fatal(w io.Writer, args ...interface{})
}); ok {
l.Fatal(a.output, args...)
} else {
a.logger.Log(a.output, args...)
}
a.FailNow()
}
// Fatalf is equivalent to [A.Logf] followed by [A.FailNow].
func (a *A) Fatalf(format string, args ...interface{}) {
if l, ok := a.logger.(interface {
Fatalf(w io.Writer, format string, args ...interface{})
}); ok {
l.Fatalf(a.output, format, args...)
} else {
a.logger.Logf(a.output, format, args...)
}
a.FailNow()
}
// FailNow marks the function as having failed
// and stops its execution by calling runtime.Goexit
// (which then runs all deferred calls in the current goroutine).
// It finishes the whole flow execution.
// FailNow must be called from the goroutine running the [Task.Action] function,
// not from other goroutines created during its execution.
// Calling FailNow does not stop those other goroutines.
func (a *A) FailNow() {
a.Fail()
runtime.Goexit()
}
// Skipped reports whether the task was skipped.
func (a *A) Skipped() bool {
a.mu.Lock()
res := a.skipped
a.mu.Unlock()
return res
}
// Skip is equivalent to [A.Log] followed by [A.SkipNow].
func (a *A) Skip(args ...interface{}) {
if l, ok := a.logger.(interface {
Skip(w io.Writer, args ...interface{})
}); ok {
l.Skip(a.output, args...)
} else {
a.logger.Log(a.output, args...)
}
a.SkipNow()
}
// Skipf is equivalent to [A.Logf] followed by [A.SkipNow].
func (a *A) Skipf(format string, args ...interface{}) {
if l, ok := a.logger.(interface {
Skipf(w io.Writer, format string, args ...interface{})
}); ok {
l.Skipf(a.output, format, args...)
} else {
a.logger.Logf(a.output, format, args...)
}
a.SkipNow()
}
// SkipNow marks the task as having been skipped
// and stops its execution by calling runtime.Goexit
// (which then runs all deferred calls in the current goroutine).
// If a test fails (see Error, Errorf, Fail) and is then skipped,
// it is still considered to have failed.
// The flow execution will continue at the next task.
// See also [A.FailNow].
// SkipNow must be called from the goroutine running the [Task.Action] function,
// not from other goroutines created during its execution.
// Calling SkipNow does not stop those other goroutines.
func (a *A) SkipNow() {
a.mu.Lock()
a.skipped = true
a.mu.Unlock()
runtime.Goexit()
}
// Helper marks the calling function as a helper function.
// It calls logger's Helper method if implemented.
// By default, when printing file and line information, that function will be skipped.
func (a *A) Helper() {
if h, ok := a.logger.(interface {
Helper()
}); ok {
h.Helper()
}
}
// Cleanup registers a function to be called when [Task.Action] function completes.
// Cleanup functions will be called in the last-added first-called order.
func (a *A) Cleanup(fn func()) {
a.mu.Lock()
a.cleanups = append(a.cleanups, fn)
a.mu.Unlock()
}
// Setenv calls os.Setenv(key, value) and uses Cleanup to restore the environment variable
// to its original value after the action.
func (a *A) Setenv(key, value string) {
a.Helper()
prevValue, ok := os.LookupEnv(key)
if err := os.Setenv(key, value); err != nil {
a.Fatalf("cannot set environment variable: %v", err)
}
if ok {
a.Cleanup(func() {
os.Setenv(key, prevValue) //nolint:errcheck // should never happen
})
} else {
a.Cleanup(func() {
os.Unsetenv(key) //nolint:errcheck // should never happen
})
}
}
// TempDir returns a temporary directory for the action to use.
// The directory is automatically removed by Cleanup when the action completes.
// Each subsequent call to TempDir returns a unique directory;
// if the directory creation fails, TempDir terminates the action by calling Fatal.
func (a *A) TempDir() string {
a.Helper()
// Drop unusual characters (such as path separators or
// characters interacting with globs) from the directory name to
// avoid surprising os.MkdirTemp behavior.
mapper := func(r rune) rune {
if r < utf8.RuneSelf {
const allowed = "!#$%&()+,-.=@^_{}~ "
if '0' <= r && r <= '9' ||
'a' <= r && r <= 'z' ||
'A' <= r && r <= 'Z' {
return r
}
if strings.ContainsRune(allowed, r) {
return r
}
} else if unicode.IsLetter(r) || unicode.IsNumber(r) {
return r
}
return -1
}
name := strings.Map(mapper, a.Name())
dir, err := ioutil.TempDir("", "goyek-"+name+"-*")
if err != nil {
a.Fatalf("cannot create temporary directory: %v", err)
}
a.Cleanup(func() {
if err := os.RemoveAll(dir); err != nil {
a.Errorf("TempDir RemoveAll cleanup: %v", err)
}
})
return dir
}
func (a *A) run(action func(a *A)) (finished bool, panicVal interface{}, panicStack []byte) {
ch := make(chan struct{})
go func() {
defer close(ch)
defer a.runCleanups(&finished, &panicVal, &panicStack)
defer func() {
if finished {
return
}
panicVal = recover()
panicStack = debug.Stack()
}()
action(a)
finished = true
}()
<-ch
return
}
func (a *A) runCleanups(finished *bool, panicVal *interface{}, panicStack *[]byte) {
// we capture only the first panic
cleanupFinished := false
if *finished {
defer func() {
if cleanupFinished {
return
}
*panicVal = recover()
*panicStack = debug.Stack()
*finished = false
}()
} else {
defer func() {
_ = recover() // ignore next panics
}()
}
// Make sure that if a cleanup function panics,
// we still run the remaining cleanup functions.
defer func() {
a.mu.Lock()
recur := len(a.cleanups) > 0
a.mu.Unlock()
if recur {
a.runCleanups(finished, panicVal, panicStack)
}
}()
for {
var cleanup func()
a.mu.Lock()
if len(a.cleanups) > 0 {
last := len(a.cleanups) - 1
cleanup = a.cleanups[last]
a.cleanups = a.cleanups[:last]
}
a.mu.Unlock()
if cleanup == nil {
cleanupFinished = true
return
}
cleanup()
}
}