aboutsummaryrefslogtreecommitdiffstats
path: root/subcmd_test.go
blob: 91c189d449bd6735e7788b8b9710473395bfd899 (plain) (blame)
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
335
336
337
338
339
340
341
342
343
344
package subcmd

import (
	"bytes"
	"context"
	"flag"
	"os"
	"strings"
	"testing"

	"git.sr.ht/~eugenetriguba/checkmate/check"
)

// mockCommand is a simple test command
type mockCommand struct {
	name       string
	synopsis   string
	usage      string
	exitStatus ExitStatus
	executed   bool
	flagValue  string
}

func (m *mockCommand) Name() string     { return m.name }
func (m *mockCommand) Synopsis() string { return m.synopsis }
func (m *mockCommand) Usage() string    { return m.usage }

func (m *mockCommand) SetFlags(f *flag.FlagSet) {
	f.StringVar(&m.flagValue, "test", "", "test flag")
}

func (m *mockCommand) Execute(ctx context.Context, f *flag.FlagSet, args ...any) ExitStatus {
	m.executed = true
	return m.exitStatus
}

func TestRegistry_Register(t *testing.T) {
	r := NewRegistry()

	cmd1 := &mockCommand{name: "test1", synopsis: "Test command 1"}
	cmd2 := &mockCommand{name: "test2", synopsis: "Test command 2"}

	r.Register(cmd1, "")
	r.Register(cmd2, "group1")

	check.Equal(t, r.Command("test1"), cmd1)
	check.Equal(t, r.Command("test2"), cmd2)
	check.Nil(t, r.Command("nonexistent"))
}

func TestRegistry_Execute_NoSubcommand(t *testing.T) {
	r := NewRegistry()
	var buf bytes.Buffer
	r.SetOutput(&buf)

	// Simulate no subcommand
	oldArgs := os.Args
	os.Args = []string{"prog"}
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	flag.Parse()
	defer func() { os.Args = oldArgs }()

	status := r.Execute(context.Background())

	check.Equal(t, status, ExitFailure)
	output := buf.String()
	check.Contains(t, output, "Usage: prog <flags> <subcommand> <subcommand args>")
	check.Contains(t, output, "Subcommands:")
}

func TestRegistry_Execute_UnknownSubcommand(t *testing.T) {
	r := NewRegistry()
	var buf bytes.Buffer
	r.SetOutput(&buf)

	oldArgs := os.Args
	os.Args = []string{"prog", "unknown"}
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	flag.Parse()
	defer func() { os.Args = oldArgs }()

	status := r.Execute(context.Background())

	check.Equal(t, status, ExitFailure)
	check.Contains(t, buf.String(), "Unknown subcommand: unknown")
}

func TestRegistry_Execute_Success(t *testing.T) {
	r := NewRegistry()
	var buf bytes.Buffer
	r.SetOutput(&buf)

	cmd := &mockCommand{
		name:       "test",
		exitStatus: ExitSuccess,
	}
	r.Register(cmd, "")

	oldArgs := os.Args
	os.Args = []string{"prog", "test"}
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	flag.Parse()
	defer func() { os.Args = oldArgs }()

	status := r.Execute(context.Background())

	check.Equal(t, status, ExitSuccess)
	check.Equal(t, cmd.executed, true)
}

func TestRegistry_Execute_WithFlags(t *testing.T) {
	r := NewRegistry()
	var buf bytes.Buffer
	r.SetOutput(&buf)

	cmd := &mockCommand{
		name:       "test",
		exitStatus: ExitSuccess,
	}
	r.Register(cmd, "")

	oldArgs := os.Args
	os.Args = []string{"prog", "test", "-test=value"}
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	flag.Parse()
	defer func() { os.Args = oldArgs }()

	status := r.Execute(context.Background())

	check.Equal(t, status, ExitSuccess)
	check.Equal(t, cmd.flagValue, "value")
}

func TestRegistry_Commands(t *testing.T) {
	r := NewRegistry()

	cmd1 := &mockCommand{name: "aaa", synopsis: "First"}
	cmd2 := &mockCommand{name: "bbb", synopsis: "Second"}
	cmd3 := &mockCommand{name: "ccc", synopsis: "Third"}

	r.Register(cmd1, "group1")
	r.Register(cmd2, "group1")
	r.Register(cmd3, "group2")

	commands := r.Commands()

	check.Equal(t, len(commands), 2)

	group1 := commands["group1"]
	check.Equal(t, len(group1), 2)

	// Check sorting
	check.Equal(t, group1[0].Name(), "aaa")
	check.Equal(t, group1[1].Name(), "bbb")

	group2 := commands["group2"]
	check.Equal(t, len(group2), 1)
}

func TestHelpCommand_NoArgs(t *testing.T) {
	r := NewRegistry()
	var buf bytes.Buffer
	r.SetOutput(&buf)

	help := &helpCommand{registry: r}
	r.Register(help, "")

	cmd1 := &mockCommand{name: "test1", synopsis: "Test command 1"}
	cmd2 := &mockCommand{name: "test2", synopsis: "Test command 2"}
	r.Register(cmd1, "group1")
	r.Register(cmd2, "group1")

	fs := flag.NewFlagSet("help", flag.ExitOnError)
	status := help.Execute(context.Background(), fs)

	check.Equal(t, status, ExitSuccess)

	output := buf.String()
	check.Contains(t, output, "Available commands")
	check.Contains(t, output, "test1")
	check.Contains(t, output, "test2")
	check.Contains(t, output, "Test command 1")
}

func TestHelpCommand_WithArg(t *testing.T) {
	r := NewRegistry()
	var buf bytes.Buffer
	r.SetOutput(&buf)

	help := &helpCommand{registry: r}
	r.Register(help, "")

	cmd := &mockCommand{
		name:  "test",
		usage: "test:\n  This is a test command\n",
	}
	r.Register(cmd, "")

	fs := flag.NewFlagSet("help", flag.ExitOnError)
	fs.Parse([]string{"test"})

	status := help.Execute(context.Background(), fs)

	check.Equal(t, status, ExitSuccess)
	check.Contains(t, buf.String(), "This is a test command")
}

func TestHelpCommand_UnknownCommand(t *testing.T) {
	r := NewRegistry()
	var buf bytes.Buffer
	r.SetOutput(&buf)

	help := &helpCommand{registry: r}

	fs := flag.NewFlagSet("help", flag.ExitOnError)
	fs.Parse([]string{"unknown"})

	status := help.Execute(context.Background(), fs)

	check.Equal(t, status, ExitFailure)
	check.Contains(t, buf.String(), "Unknown command: unknown")
}

func TestCommandsCommand(t *testing.T) {
	r := NewRegistry()
	var buf bytes.Buffer
	r.SetOutput(&buf)

	cmds := &commandsCommand{registry: r}
	r.Register(cmds, "")

	r.Register(&mockCommand{name: "zzz"}, "")
	r.Register(&mockCommand{name: "aaa"}, "")
	r.Register(&mockCommand{name: "mmm"}, "")

	fs := flag.NewFlagSet("commands", flag.ExitOnError)
	status := cmds.Execute(context.Background(), fs)

	check.Equal(t, status, ExitSuccess)

	output := buf.String()
	lines := strings.Split(strings.TrimSpace(output), "\n")

	// Should be sorted alphabetically
	check.Equal(t, len(lines), 4)

	expected := []string{"aaa", "commands", "mmm", "zzz"}
	for i, line := range lines {
		check.Equal(t, line, expected[i])
	}
}

func TestFlagsCommand_NoFlags(t *testing.T) {
	// Create a clean flag set
	oldCommandLine := flag.CommandLine
	flag.CommandLine = flag.NewFlagSet("test", flag.ExitOnError)
	defer func() { flag.CommandLine = oldCommandLine }()

	r := NewRegistry()
	var buf bytes.Buffer
	r.SetOutput(&buf)

	flags := &flagsCommand{registry: r}

	fs := flag.NewFlagSet("flags", flag.ExitOnError)
	status := flags.Execute(context.Background(), fs)

	check.Equal(t, status, ExitSuccess)
	check.Contains(t, buf.String(), "No top-level flags defined")
}

func TestFlagsCommand_WithFlags(t *testing.T) {
	// Create a clean flag set with a test flag
	oldCommandLine := flag.CommandLine
	flag.CommandLine = flag.NewFlagSet("test", flag.ExitOnError)
	flag.String("testflag", "default", "test flag description")
	defer func() { flag.CommandLine = oldCommandLine }()

	r := NewRegistry()
	var buf bytes.Buffer
	r.SetOutput(&buf)

	flags := &flagsCommand{registry: r}

	fs := flag.NewFlagSet("flags", flag.ExitOnError)
	status := flags.Execute(context.Background(), fs)

	check.Equal(t, status, ExitSuccess)

	output := buf.String()
	check.Contains(t, output, "testflag")
	check.Contains(t, output, "test flag description")
}

func TestPackageLevelFunctions(t *testing.T) {
	// Save and restore default registry
	oldRegistry := defaultRegistry
	defer func() { defaultRegistry = oldRegistry }()

	defaultRegistry = NewRegistry()
	var buf bytes.Buffer
	SetOutput(&buf)

	cmd := &mockCommand{
		name:       "test",
		synopsis:   "Test command",
		exitStatus: ExitSuccess,
	}

	Register(cmd, "group1")

	// Test Commands()
	commands := Commands()
	check.Equal(t, len(commands["group1"]), 1)

	// Verify command is registered (use registry method)
	check.Equal(t, defaultRegistry.Command("test"), cmd)

	// Test Execute()
	oldArgs := os.Args
	os.Args = []string{"prog", "test"}
	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
	flag.Parse()
	defer func() { os.Args = oldArgs }()

	status := Execute(context.Background())
	check.Equal(t, status, ExitSuccess)
}

func TestExitStatus(t *testing.T) {
	check.Equal(t, int(ExitSuccess), 0)
	check.Equal(t, int(ExitFailure), 1)
}

func TestBuiltInCommands(t *testing.T) {
	help := HelpCommand()
	check.Equal(t, help.Name(), "help")

	commands := CommandsCommand()
	check.Equal(t, commands.Name(), "commands")

	flags := FlagsCommand()
	check.Equal(t, flags.Name(), "flags")
}