diff options
| author | Eugene Triguba <hello@eugenetriguba.com> | 2025-12-27 05:26:39 -0500 |
|---|---|---|
| committer | Eugene Triguba <hello@eugenetriguba.com> | 2025-12-27 05:26:39 -0500 |
| commit | 8373aff9ebc6a177c3a3e30e58758fd2e621c352 (patch) | |
| tree | a08c66fffa42166ee4c872815c355719519405c4 | |
| parent | Update checkmate to v0.5.0 (diff) | |
| download | subcmd-8373aff9ebc6a177c3a3e30e58758fd2e621c352.zip | |
Refactor tests to reduce duplication
| -rw-r--r-- | subcmd_test.go | 276 |
1 files changed, 121 insertions, 155 deletions
diff --git a/subcmd_test.go b/subcmd_test.go index 91c189d..6841f9e 100644 --- a/subcmd_test.go +++ b/subcmd_test.go @@ -8,10 +8,10 @@ import ( "strings" "testing" + "git.sr.ht/~eugenetriguba/checkmate/assert" "git.sr.ht/~eugenetriguba/checkmate/check" ) -// mockCommand is a simple test command type mockCommand struct { name string synopsis string @@ -24,19 +24,53 @@ type mockCommand struct { 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) { +// testRegistryOption configures a test registry. +type testRegistryOption func(*Registry) + +// withCommand adds a command to the registry. +func withCommand(cmd Command, group string) testRegistryOption { + return func(r *Registry) { + r.Register(cmd, group) + } +} + +// withBuffer sets the output writer for the registry. +func withBuffer(buf *bytes.Buffer) testRegistryOption { + return func(r *Registry) { + r.SetOutput(buf) + } +} + +// newTestRegistry creates a registry configured for testing with +// the given options. +func newTestRegistry(opts ...testRegistryOption) *Registry { r := NewRegistry() + for _, opt := range opts { + opt(r) + } + return r +} + +// setupOsArgs sets up os.Args and flag.CommandLine for testing, +// returning a cleanup function that restores the original state. +func setupOsArgs(args ...string) func() { + oldArgs := os.Args + os.Args = args + flag.CommandLine = flag.NewFlagSet(args[0], flag.ExitOnError) + flag.Parse() + return func() { os.Args = oldArgs } +} +func TestRegistry_Register(t *testing.T) { + r := NewRegistry() cmd1 := &mockCommand{name: "test1", synopsis: "Test command 1"} cmd2 := &mockCommand{name: "test2", synopsis: "Test command 2"} @@ -49,16 +83,10 @@ func TestRegistry_Register(t *testing.T) { } 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 }() + r := newTestRegistry(withBuffer(&buf)) + cleanup := setupOsArgs("prog") + defer cleanup() status := r.Execute(context.Background()) @@ -69,15 +97,10 @@ func TestRegistry_Execute_NoSubcommand(t *testing.T) { } 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 }() + r := newTestRegistry(withBuffer(&buf)) + cleanup := setupOsArgs("prog", "unknown") + defer cleanup() status := r.Execute(context.Background()) @@ -86,21 +109,17 @@ func TestRegistry_Execute_UnknownSubcommand(t *testing.T) { } 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 }() + r := newTestRegistry( + withBuffer(&buf), + withCommand(cmd, ""), + ) + cleanup := setupOsArgs("prog", "test") + defer cleanup() status := r.Execute(context.Background()) @@ -109,21 +128,14 @@ func TestRegistry_Execute_Success(t *testing.T) { } 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 }() + r := newTestRegistry(withBuffer(&buf), withCommand(cmd, "")) + cleanup := setupOsArgs("prog", "test", "-test=value") + defer cleanup() status := r.Execute(context.Background()) @@ -132,15 +144,14 @@ func TestRegistry_Execute_WithFlags(t *testing.T) { } 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") + r := newTestRegistry( + withCommand(cmd2, "group1"), + withCommand(cmd1, "group1"), + withCommand(cmd3, "group2"), + ) commands := r.Commands() @@ -148,8 +159,7 @@ func TestRegistry_Commands(t *testing.T) { group1 := commands["group1"] check.Equal(t, len(group1), 2) - - // Check sorting + // Should be in alphabetical order check.Equal(t, group1[0].Name(), "aaa") check.Equal(t, group1[1].Name(), "bbb") @@ -157,24 +167,51 @@ func TestRegistry_Commands(t *testing.T) { check.Equal(t, len(group2), 1) } -func TestHelpCommand_NoArgs(t *testing.T) { - r := NewRegistry() - var buf bytes.Buffer - r.SetOutput(&buf) +func TestPackageLevelConvienanceFunctionsUseDefaultRegistry(t *testing.T) { + cmd := &mockCommand{name: "test", synopsis: "Test"} - help := &helpCommand{registry: r} - r.Register(help, "") + Register(cmd, "group") + check.Equal(t, defaultRegistry.Command("test"), cmd) + + cleanup := setupOsArgs("prog", "test") + defer cleanup() + status := Execute(context.Background()) + check.Equal(t, status, ExitSuccess) + check.Equal(t, cmd.executed, true) +} + +func TestBuiltInCommandNames(t *testing.T) { + help := HelpCommand() + check.Equal(t, help.Name(), "help") + + manHelp := ManHelpCommand("myapp") + check.Equal(t, manHelp.Name(), "help") + commands := CommandsCommand() + check.Equal(t, commands.Name(), "commands") + + flags := FlagsCommand() + check.Equal(t, flags.Name(), "flags") +} + +func TestHelpCommand_NoArgs(t *testing.T) { + var buf bytes.Buffer cmd1 := &mockCommand{name: "test1", synopsis: "Test command 1"} cmd2 := &mockCommand{name: "test2", synopsis: "Test command 2"} - r.Register(cmd1, "group1") - r.Register(cmd2, "group1") - + r := newTestRegistry( + withBuffer(&buf), + withCommand(cmd1, "group1"), + withCommand(cmd2, "group1"), + ) + help := &helpCommand{registry: r} + r.Register(help, "") fs := flag.NewFlagSet("help", flag.ExitOnError) + err := fs.Parse([]string{}) + assert.Nil(t, err) + 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") @@ -183,35 +220,27 @@ func TestHelpCommand_NoArgs(t *testing.T) { } 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, "") - + r := newTestRegistry(withBuffer(&buf), withCommand(cmd, "")) + help := &helpCommand{registry: r} + r.Register(help, "") 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") + check.Equal(t, buf.String(), cmd.usage+"\n") } func TestHelpCommand_UnknownCommand(t *testing.T) { - r := NewRegistry() var buf bytes.Buffer - r.SetOutput(&buf) - + r := newTestRegistry(withBuffer(&buf)) help := &helpCommand{registry: r} - fs := flag.NewFlagSet("help", flag.ExitOnError) fs.Parse([]string{"unknown"}) @@ -222,28 +251,24 @@ func TestHelpCommand_UnknownCommand(t *testing.T) { } func TestCommandsCommand(t *testing.T) { - r := NewRegistry() var buf bytes.Buffer - r.SetOutput(&buf) - + r := newTestRegistry( + withBuffer(&buf), + withCommand(&mockCommand{name: "zzz"}, ""), + withCommand(&mockCommand{name: "aaa"}, ""), + withCommand(&mockCommand{name: "mmm"}, ""), + ) 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) - + // Should be sorted alphabetically expected := []string{"aaa", "commands", "mmm", "zzz"} for i, line := range lines { check.Equal(t, line, expected[i]) @@ -251,18 +276,11 @@ func TestCommandsCommand(t *testing.T) { } 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) - + r := newTestRegistry(withBuffer(&buf)) flags := &flagsCommand{registry: r} - fs := flag.NewFlagSet("flags", flag.ExitOnError) + status := flags.Execute(context.Background(), fs) check.Equal(t, status, ExitSuccess) @@ -270,75 +288,23 @@ func TestFlagsCommand_NoFlags(t *testing.T) { } 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) - + r := newTestRegistry(withBuffer(&buf)) + fs := flag.NewFlagSet("flags", flag.ExitOnError) + flag.String("testflag", "default", "test flag description") 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.Equal( + t, + output, + `Top-level flags: + -testflag (default: default) + test flag description +`) 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") -} |