1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package zap
22
23 import (
24 "flag"
25 "io"
26 "testing"
27
28 "go.uber.org/zap/zapcore"
29
30 "github.com/stretchr/testify/assert"
31 )
32
33 type flagTestCase struct {
34 args []string
35 wantLevel zapcore.Level
36 wantErr bool
37 }
38
39 func (tc flagTestCase) runImplicitSet(t testing.TB) {
40 origCommandLine := flag.CommandLine
41 flag.CommandLine = flag.NewFlagSet("test", flag.ContinueOnError)
42 flag.CommandLine.SetOutput(io.Discard)
43 defer func() { flag.CommandLine = origCommandLine }()
44
45 level := LevelFlag("level", InfoLevel, "")
46 tc.run(t, flag.CommandLine, level)
47 }
48
49 func (tc flagTestCase) runExplicitSet(t testing.TB) {
50 var lvl zapcore.Level
51 set := flag.NewFlagSet("test", flag.ContinueOnError)
52 set.SetOutput(io.Discard)
53 set.Var(&lvl, "level", "minimum enabled logging level")
54 tc.run(t, set, &lvl)
55 }
56
57 func (tc flagTestCase) run(t testing.TB, set *flag.FlagSet, actual *zapcore.Level) {
58 err := set.Parse(tc.args)
59 if tc.wantErr {
60 assert.Error(t, err, "Parse(%v) should fail.", tc.args)
61 return
62 }
63 if assert.NoError(t, err, "Parse(%v) should succeed.", tc.args) {
64 assert.Equal(t, tc.wantLevel, *actual, "Level mismatch.")
65 }
66 }
67
68 func TestLevelFlag(t *testing.T) {
69 tests := []flagTestCase{
70 {
71 args: nil,
72 wantLevel: zapcore.InfoLevel,
73 },
74 {
75 args: []string{"--level", "unknown"},
76 wantErr: true,
77 },
78 {
79 args: []string{"--level", "error"},
80 wantLevel: zapcore.ErrorLevel,
81 },
82 }
83
84 for _, tt := range tests {
85 tt.runExplicitSet(t)
86 tt.runImplicitSet(t)
87 }
88 }
89
90 func TestLevelFlagsAreIndependent(t *testing.T) {
91 origCommandLine := flag.CommandLine
92 flag.CommandLine = flag.NewFlagSet("test", flag.ContinueOnError)
93 flag.CommandLine.SetOutput(io.Discard)
94 defer func() { flag.CommandLine = origCommandLine }()
95
96
97 fileLevel := LevelFlag("file-level", InfoLevel, "")
98 consoleLevel := LevelFlag("console-level", InfoLevel, "")
99
100 assert.NoError(t, flag.CommandLine.Parse([]string{"-file-level", "debug"}), "Unexpected flag-parsing error.")
101 assert.Equal(t, InfoLevel, *consoleLevel, "Expected file logging level to remain unchanged.")
102 assert.Equal(t, DebugLevel, *fileLevel, "Expected console logging level to have changed.")
103 }
104
View as plain text