diff --git a/internal/pkg/conflictless/cli.go b/internal/pkg/conflictless/cli.go index 57742da..2479e19 100644 --- a/internal/pkg/conflictless/cli.go +++ b/internal/pkg/conflictless/cli.go @@ -56,7 +56,7 @@ func argsWithoutTestFlags() []string { for _, arg := range os.Args { if strings.HasPrefix(arg, "-test.") { - break + continue } args = append(args, arg) diff --git a/internal/pkg/conflictless/cli_test.go b/internal/pkg/conflictless/cli_test.go index eb4f503..a2c2491 100644 --- a/internal/pkg/conflictless/cli_test.go +++ b/internal/pkg/conflictless/cli_test.go @@ -2,6 +2,7 @@ package conflictless_test import ( "errors" + "net/url" "os" "os/exec" "testing" @@ -51,3 +52,66 @@ func TestCLIWithoutArguments(t *testing.T) { assert.Equal(t, expectedCode, exitCode, "process exited with %d, want exit status %d", expectedCode, exitCode) } + +func TestCLIHelp(t *testing.T) { + t.Parallel() + + if os.Getenv("TEST_CLI_HELP") != "" { + conflictless.CLI() + + return + } + + for _, testCase := range []struct { + description string + args []string + isError bool + }{ + {"help", []string{"help"}, false}, + {"help check", []string{"help", "check"}, false}, + {"help generate", []string{"help", "generate"}, false}, + {"help unknown", []string{"help", "unknown"}, true}, + } { + // Reinitialise testCase for parallel testing. + testCase := testCase + + t.Run(testCase.description, func(t *testing.T) { + t.Parallel() + + stdoutFile := createTempFile(t, os.TempDir(), "test-cli-"+url.QueryEscape(testCase.description)+"-stdout") + defer os.Remove(stdoutFile.Name()) + + stderrFile := createTempFile(t, os.TempDir(), "test-cli-"+url.QueryEscape(testCase.description)+"-stderr") + defer os.Remove(stderrFile.Name()) + + //nolint:gosec // this is a test package so G204 doesn't really matter here. + cmd := exec.Command(os.Args[0], append([]string{"-test.run=^TestCLIHelp$"}, testCase.args...)...) + cmd.Env = append(os.Environ(), "TEST_CLI_HELP=1") + cmd.Stdout = stdoutFile + cmd.Stderr = stderrFile + + err := cmd.Run() + + if testCase.isError { + assert.Error(t, err) + assert.IsType(t, new(exec.ExitError), err) + } else { + assert.NoError(t, err) + } + + stderrData, err := os.ReadFile(stderrFile.Name()) + assert.NoError(t, err) + + stdoutData, err := os.ReadFile(stdoutFile.Name()) + assert.NoError(t, err) + + if testCase.isError { + assert.Empty(t, string(stdoutData)) + assert.Contains(t, string(stderrData), "Error:") + } else { + assert.Contains(t, string(stdoutData), "Usage: conflictless") + assert.Empty(t, string(stderrData)) + } + }) + } +} diff --git a/internal/pkg/conflictless/help.go b/internal/pkg/conflictless/help.go index ad734b1..269591b 100644 --- a/internal/pkg/conflictless/help.go +++ b/internal/pkg/conflictless/help.go @@ -23,7 +23,6 @@ func help() { usage() default: PrintErrorAndExit(fmt.Sprintf("unknown help topic '%s'", topic), func() {}) - os.Exit(exitCodeMisuseError) } os.Exit(exitCodeSuccess)