Files
secret/internal/cli/usage_test.go
T
sneak 24be2f556c
check / check (push) Failing after 2s
Print usage only for a command called wrongly (closes #41)
A failed command printed the whole usage text after its error, burying
it. The root command's PersistentPreRunE now turns usage off once cobra
has checked the arguments and flags, so an error from running the
command is printed once on its own. Wrong arity, an unknown flag, a bad
flag value and a missing required flag still get usage; cobra checks
required flags after that hook, so the hook checks them first. Root
SilenceUsage was not used: in this cobra version it hides usage for
argument and flag errors too. Cobra still prints the error; Entry is
unchanged.

Model: opus-5-5
2026-10-04 07:43:33 +00:00

47 lines
1.4 KiB
Go

package cli_test
import (
"strings"
"testing"
"git.eeqj.de/sneak/secret/internal/cli"
"git.eeqj.de/sneak/secret/internal/secret"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// usageHeading starts the usage text cobra prints after an error.
const usageHeading = "Usage:"
// A command called wrongly gets usage after its error; a command that
// fails while running gets its error alone. Either way the command fails
// and its error is shown exactly once.
//
//nolint:paralleltest // executes the CLI in-process and sets the environment
func TestUsageOnlyForCallErrors(t *testing.T) {
// No vault in the state directory, so `get x` fails while running.
env := map[string]string{secret.EnvStateDir: t.TempDir()}
tests := []struct {
call string
wantUsage bool
}{
{call: "get", wantUsage: true},
{call: "get x y", wantUsage: true},
{call: "get --no-such-flag x", wantUsage: true},
{call: "generate secret x --length abc", wantUsage: true},
{call: "import x", wantUsage: true},
{call: "get x", wantUsage: false},
}
for _, tt := range tests {
output, err := cli.ExecuteCommandInProcess(strings.Fields(tt.call), "", env)
require.Error(t, err, "%q should fail", tt.call)
assert.Equal(t, 1, strings.Count(output, err.Error()),
"%q should show its error once:\n%s", tt.call, output)
assert.Equal(t, tt.wantUsage, strings.Contains(output, usageHeading),
"usage shown for %q:\n%s", tt.call, output)
}
}