-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexit_test.go
More file actions
115 lines (95 loc) · 2.48 KB
/
exit_test.go
File metadata and controls
115 lines (95 loc) · 2.48 KB
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
package cli
import (
"bytes"
"context"
"errors"
"io"
"os"
"testing"
"github.com/krostar/test"
)
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(test.Context(t), nil,
WithExitFunc(func(status int) {
exitStatus = &status
}),
WithExitLoggerFunc(func(context.Context) io.WriteCloser {
return &exitMessage
}),
)
test.Require(t, exitStatus != nil)
test.Assert(t, *exitStatus == 0)
test.Assert(t, exitMessage.String() == "")
test.Assert(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(test.Context(t), errors.New("boom"),
WithExitFunc(func(status int) {
exitStatus = &status
}),
WithExitLoggerFunc(func(context.Context) io.WriteCloser {
return &exitMessage
}),
)
test.Require(t, exitStatus != nil)
test.Assert(t, *exitStatus == 255)
test.Assert(t, exitMessage.String() == "boom\n")
test.Assert(t, exitMessage.Closed())
})
t.Run("with custom status", func(t *testing.T) {
var (
exitStatus *int
exitMessage bufferThatCloses
)
Exit(test.Context(t), NewErrorWithExitStatus(errors.New("boom"), 42),
WithExitFunc(func(status int) {
exitStatus = &status
}),
WithExitLoggerFunc(func(context.Context) io.WriteCloser {
return &exitMessage
}),
)
test.Require(t, exitStatus != nil)
test.Assert(t, *exitStatus == 42)
test.Assert(t, exitMessage.String() == "boom\n")
test.Assert(t, exitMessage.Closed())
})
})
}
func Test_ExitOption(t *testing.T) {
o := new(exitOptions)
WithExitFunc(os.Exit)(o)
test.Require(t, o.exitFunc != nil)
WithExitLoggerFunc(getExitLoggerFromMetadata)(o)
test.Require(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) {
test.Require(t, getExitLoggerFromMetadata(test.Context(t)) != nil)
})
t.Run("set a logger", func(t *testing.T) {
ctx := NewContextWithMetadata(test.Context(t))
logger := new(bufferThatCloses)
SetExitLoggerInMetadata(ctx, logger)
test.Assert(t, getExitLoggerFromMetadata(ctx) == logger)
})
}