-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclix_test.go
More file actions
321 lines (279 loc) · 9.7 KB
/
Copy pathclix_test.go
File metadata and controls
321 lines (279 loc) · 9.7 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
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
package clix
import (
"context"
"errors"
"strings"
"testing"
"github.com/spf13/cobra"
)
func TestVersionString(t *testing.T) {
app := App{
Version: "1.2.3",
Commit: "abc123",
Date: "2026-03-04",
BuiltBy: "ci",
}
got := app.VersionString()
want := "1.2.3 (Commit: abc123) (Date: 2026-03-04) (Built by: ci)"
if got != want {
t.Errorf("VersionString() = %q, want %q", got, want)
}
}
func TestVersionStringDefaults(t *testing.T) {
app := App{}
got := app.VersionString()
want := "dev (Commit: none) (Date: unknown) (Built by: local)"
if got != want {
t.Errorf("VersionString() = %q, want %q", got, want)
}
}
func TestRunRegistersFlags(t *testing.T) {
// Reset package-level flag state
defer func() {
JSONOutput = false
Verbose = false
DryRun = false
Silent = false
}()
ran := false
cmd := &cobra.Command{
Use: "test",
RunE: func(cmd *cobra.Command, args []string) error {
ran = true
return nil
},
}
app := App{Version: "1.0.0"}
err := app.Run(cmd)
if err != nil {
t.Fatalf("Run() error = %v", err)
}
if !ran {
t.Error("command RunE was not called")
}
if cmd.PersistentFlags().Lookup("json") == nil {
t.Error("--json flag not registered")
}
if cmd.PersistentFlags().Lookup("verbose") == nil {
t.Error("--verbose flag not registered")
}
if cmd.PersistentFlags().Lookup("dry-run") == nil {
t.Error("--dry-run flag not registered")
}
if cmd.PersistentFlags().Lookup("silent") == nil {
t.Error("--silent flag not registered")
}
}
// TestRunTwiceOnSameRootIsRepeatable pins that App.Run can execute the same
// cobra root more than once. cobra merges a root's persistent flags into its
// local flag set the first time it executes, so after that first run the
// reserved flags clix registered turn up in both flag sets; a naive second
// registerFlags call would see them as a collision against itself and refuse
// to run. Both executions must succeed, and the flags must keep working.
func TestRunTwiceOnSameRootIsRepeatable(t *testing.T) {
t.Cleanup(func() { JSONOutput, Verbose, DryRun, Silent = false, false, false, false })
var seenJSON []bool
cmd := &cobra.Command{
Use: "test",
RunE: func(*cobra.Command, []string) error {
seenJSON = append(seenJSON, JSONOutput)
return nil
},
}
app := &App{Version: "1.0.0"}
cmd.SetArgs(nil)
if err := runNoPanic(t, app, cmd); err != nil {
t.Fatalf("first Run() error = %v", err)
}
cmd.SetArgs([]string{"--json"})
if err := runNoPanic(t, app, cmd); err != nil {
t.Fatalf("second Run() error = %v", err)
}
if len(seenJSON) != 2 {
t.Fatalf("RunE ran %d times, want 2", len(seenJSON))
}
if seenJSON[0] {
t.Errorf("JSONOutput = true on first run, want false (no --json passed)")
}
if !seenJSON[1] {
t.Errorf("JSONOutput = false on second run, want true (--json passed)")
}
}
// TestRunTwiceOnSameRootJSONTrueThenFalseIsolatesState pins the fix for a
// reliability gap: a --json invocation must not leak into a later
// invocation on the same root that passes no --json flag. Before the fix,
// registerFlags reused the earlier invocation's *pflag.Flag without
// resetting its value or Changed bit, so the second invocation observed
// JSONOutput == true even though it never asked for JSON output.
func TestRunTwiceOnSameRootJSONTrueThenFalseIsolatesState(t *testing.T) {
t.Cleanup(func() { JSONOutput, Verbose, DryRun, Silent = false, false, false, false })
var seenJSON []bool
cmd := &cobra.Command{
Use: "test",
RunE: func(*cobra.Command, []string) error {
seenJSON = append(seenJSON, JSONOutput)
return nil
},
}
app := &App{Version: "1.0.0"}
cmd.SetArgs([]string{"--json"})
if err := runNoPanic(t, app, cmd); err != nil {
t.Fatalf("first Run() error = %v", err)
}
cmd.SetArgs(nil)
if err := runNoPanic(t, app, cmd); err != nil {
t.Fatalf("second Run() error = %v", err)
}
if len(seenJSON) != 2 {
t.Fatalf("RunE ran %d times, want 2", len(seenJSON))
}
if !seenJSON[0] {
t.Errorf("JSONOutput = false on first run, want true (--json passed)")
}
if seenJSON[1] {
t.Errorf("JSONOutput = true on second run, want false (no --json passed); stale state leaked across invocations")
}
if got := cmd.PersistentFlags().Lookup("json").Changed; got {
t.Errorf("--json Changed = true after the second run, want false: stale Changed leaked across invocations")
}
}
// TestRunTwice_StaleChangedDoesNotSuppressViper pins that a stale Changed bit
// carried over from an earlier invocation cannot suppress a later
// invocation's viper-provided value, while an explicit flag on the current
// invocation still wins over viper (the command-line-over-viper precedence
// BindViper documents).
func TestRunTwice_StaleChangedDoesNotSuppressViper(t *testing.T) {
restoreFlagState(t)
writeViperConfig(t, "json: true\n")
var seenJSON []bool
cmd := &cobra.Command{
Use: "test",
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
return BindViper(cmd)
},
RunE: func(*cobra.Command, []string) error {
seenJSON = append(seenJSON, JSONOutput)
return nil
},
}
app := &App{Version: "1.0.0"}
// First invocation: an explicit --json=false beats viper's json: true
// and leaves the flag Changed.
cmd.SetArgs([]string{"--json=false"})
if err := runNoPanic(t, app, cmd); err != nil {
t.Fatalf("first Run() error = %v", err)
}
// Second invocation: no --json flag at all. Without resetting the stale
// Changed=true left by the first invocation, BindViper's guard would
// wrongly treat this invocation as having an explicit flag too,
// suppressing viper's json: true.
cmd.SetArgs(nil)
if err := runNoPanic(t, app, cmd); err != nil {
t.Fatalf("second Run() error = %v", err)
}
// Third invocation: an explicit --json=false must still beat viper.
cmd.SetArgs([]string{"--json=false"})
if err := runNoPanic(t, app, cmd); err != nil {
t.Fatalf("third Run() error = %v", err)
}
if len(seenJSON) != 3 {
t.Fatalf("RunE ran %d times, want 3", len(seenJSON))
}
if seenJSON[0] {
t.Errorf("JSONOutput = true on first run, want false (explicit --json=false beats viper)")
}
if !seenJSON[1] {
t.Errorf("JSONOutput = false on second run, want true (viper's json: true should apply once stale Changed is reset)")
}
if seenJSON[2] {
t.Errorf("JSONOutput = true on third run, want false (explicit --json=false beats viper again)")
}
}
func TestRunContextPropagatesCancellation(t *testing.T) {
defer func() {
JSONOutput = false
Verbose = false
DryRun = false
Silent = false
}()
ctx, cancel := context.WithCancel(context.Background())
cancel() // cancel before the command runs
cmd := &cobra.Command{
Use: "test",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Context().Err()
},
}
app := App{Version: "1.0.0"}
err := app.RunContext(ctx, cmd)
if !errors.Is(err, context.Canceled) {
t.Fatalf("RunContext() error = %v, want context.Canceled", err)
}
}
// runNoPanic calls app.Run(cmd) and converts a panic into an explicit test
// failure, so a regression to pflag's "flag redefined" panic is reported
// rather than crashing the test binary.
func runNoPanic(t *testing.T, app *App, cmd *cobra.Command) (err error) {
t.Helper()
defer func() {
if r := recover(); r != nil {
t.Fatalf("Run() panicked: %v", r)
}
}()
return app.Run(cmd)
}
func TestRunNilCommandReturnsError(t *testing.T) {
err := runNoPanic(t, &App{}, nil)
if err == nil {
t.Fatal("Run(nil) = nil error, want contextual error")
}
if got, want := err.Error(), "clix: Run: root command is nil"; got != want {
t.Errorf("Run(nil) error = %q, want %q", got, want)
}
}
func TestRunReservedShorthandCollisionReturnsError(t *testing.T) {
t.Cleanup(func() { JSONOutput, Verbose, DryRun, Silent = false, false, false, false })
var name string
cmd := &cobra.Command{Use: "test", RunE: func(*cobra.Command, []string) error { return nil }}
cmd.PersistentFlags().StringVarP(&name, "name", "n", "", "consumer flag using clix's -n")
err := runNoPanic(t, &App{Version: "1.0.0"}, cmd)
if err == nil {
t.Fatal("Run() = nil error, want reserved-shorthand collision error")
}
for _, want := range []string{"clix:", "-n", "--name"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("Run() error = %q, want it to mention %q", err, want)
}
}
if cmd.PersistentFlags().Lookup("dry-run") != nil {
t.Error("--dry-run was registered despite the shorthand collision")
}
}
func TestRunReservedNameCollisionReturnsError(t *testing.T) {
t.Cleanup(func() { JSONOutput, Verbose, DryRun, Silent = false, false, false, false })
var jsonPath string
cmd := &cobra.Command{Use: "test", RunE: func(*cobra.Command, []string) error { return nil }}
cmd.PersistentFlags().StringVar(&jsonPath, "json", "", "consumer flag using clix's --json")
err := runNoPanic(t, &App{Version: "1.0.0"}, cmd)
if err == nil {
t.Fatal("Run() = nil error, want reserved-flag collision error")
}
if !strings.Contains(err.Error(), "--json") || !strings.Contains(err.Error(), "clix:") {
t.Errorf("Run() error = %q, want it to name --json", err)
}
}
func TestRunReservedLocalFlagCollisionReturnsError(t *testing.T) {
t.Cleanup(func() { JSONOutput, Verbose, DryRun, Silent = false, false, false, false })
// A root-local (non-persistent) flag collides too: cobra merges the local
// and persistent sets at parse time, so pflag would panic there instead.
var silent bool
cmd := &cobra.Command{Use: "test", RunE: func(*cobra.Command, []string) error { return nil }}
cmd.Flags().BoolVarP(&silent, "quiet", "s", false, "consumer flag using clix's -s")
err := runNoPanic(t, &App{Version: "1.0.0"}, cmd)
if err == nil {
t.Fatal("Run() = nil error, want reserved-shorthand collision error for local flag")
}
if !strings.Contains(err.Error(), "-s") || !strings.Contains(err.Error(), "--quiet") {
t.Errorf("Run() error = %q, want it to mention -s and --quiet", err)
}
}