-
Notifications
You must be signed in to change notification settings - Fork 0
/
exit_test.go
114 lines (95 loc) · 2.51 KB
/
exit_test.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
package cli
import (
"bytes"
"context"
"errors"
"io"
"os"
"testing"
"gotest.tools/v3/assert"
)
type bufferThatCloses struct {
bytes.Buffer
closed bool
}
func (l *bufferThatCloses) Close() error {
l.closed = true
return nil
}
func (l *bufferThatCloses) Closed() bool { return l.closed }
func Test_Exit(t *testing.T) {
t.Run("no error", func(t *testing.T) {
var (
exitStatus *int
exitMessage bufferThatCloses
)
Exit(context.Background(), nil,
WithExitFunc(func(status int) {
exitStatus = &status
}),
WithExitLoggerFunc(func(context.Context) io.WriteCloser {
return &exitMessage
}),
)
assert.Assert(t, exitStatus != nil)
assert.Check(t, *exitStatus == 0)
assert.Check(t, exitMessage.String() == "")
assert.Check(t, exitMessage.Closed())
})
t.Run("error", func(t *testing.T) {
t.Run("without additional behavior", func(t *testing.T) {
var (
exitStatus *int
exitMessage bufferThatCloses
)
Exit(context.Background(), errors.New("boom"),
WithExitFunc(func(status int) {
exitStatus = &status
}),
WithExitLoggerFunc(func(context.Context) io.WriteCloser {
return &exitMessage
}),
)
assert.Assert(t, exitStatus != nil)
assert.Check(t, *exitStatus == 255)
assert.Check(t, exitMessage.String() == "boom\n")
assert.Check(t, exitMessage.Closed())
})
t.Run("with custom status", func(t *testing.T) {
var (
exitStatus *int
exitMessage bufferThatCloses
)
Exit(context.Background(), NewErrorWithExitStatus(errors.New("boom"), 42),
WithExitFunc(func(status int) {
exitStatus = &status
}),
WithExitLoggerFunc(func(context.Context) io.WriteCloser {
return &exitMessage
}),
)
assert.Assert(t, exitStatus != nil)
assert.Check(t, *exitStatus == 42)
assert.Check(t, exitMessage.String() == "boom\n")
assert.Check(t, exitMessage.Closed())
})
})
}
func Test_ExitOption(t *testing.T) {
o := new(exitOptions)
WithExitFunc(os.Exit)(o)
assert.Assert(t, o.exitFunc != nil)
WithExitLoggerFunc(getExitLoggerFromMetadata)(o)
assert.Assert(t, o.getLoggerFunc != nil)
}
func Test_loggerInMetadata(t *testing.T) {
t.Run("get a logger even if none is previously set", func(t *testing.T) {
assert.Assert(t, getExitLoggerFromMetadata(context.Background()) != nil)
})
t.Run("set a logger", func(t *testing.T) {
ctx := NewContextWithMetadata(context.Background())
logger := new(bufferThatCloses)
SetExitLoggerInMetadata(ctx, logger)
assert.Check(t, getExitLoggerFromMetadata(ctx) == logger)
})
}