Exit non-zero if a unknown subcommand is given
Currently it just prints the help message and exits 0. We do this by modifying the helpCommand and helpSubcommand cli.Commands to return an error if they are called with an unknown subcommand. This propogates up to the app which exits with 3 and prints the error. Thanks to @danslimmon for the initial approach! Fixes #276
This commit is contained in:
58
help_test.go
58
help_test.go
@@ -2,6 +2,8 @@ package cli
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -110,3 +112,59 @@ func Test_Version_Custom_Flags(t *testing.T) {
|
||||
t.Errorf("unexpected output: %s", output.String())
|
||||
}
|
||||
}
|
||||
|
||||
func Test_helpCommand_Action_ErrorIfNoTopic(t *testing.T) {
|
||||
app := NewApp()
|
||||
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
set.Parse([]string{"foo"})
|
||||
|
||||
c := NewContext(app, set, nil)
|
||||
|
||||
err := helpCommand.Action.(func(*Context) error)(c)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("expected error from helpCommand.Action(), but got nil")
|
||||
}
|
||||
|
||||
exitErr, ok := err.(*ExitError)
|
||||
if !ok {
|
||||
t.Fatalf("expected ExitError from helpCommand.Action(), but instead got: %v", err.Error())
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(exitErr.Error(), "No help topic for") {
|
||||
t.Fatalf("expected an unknown help topic error, but got: %v", exitErr.Error())
|
||||
}
|
||||
|
||||
if exitErr.exitCode != 3 {
|
||||
t.Fatalf("expected exit value = 3, got %d instead", exitErr.exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_helpSubcommand_Action_ErrorIfNoTopic(t *testing.T) {
|
||||
app := NewApp()
|
||||
|
||||
set := flag.NewFlagSet("test", 0)
|
||||
set.Parse([]string{"foo"})
|
||||
|
||||
c := NewContext(app, set, nil)
|
||||
|
||||
err := helpSubcommand.Action.(func(*Context) error)(c)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("expected error from helpCommand.Action(), but got nil")
|
||||
}
|
||||
|
||||
exitErr, ok := err.(*ExitError)
|
||||
if !ok {
|
||||
t.Fatalf("expected ExitError from helpCommand.Action(), but instead got: %v", err.Error())
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(exitErr.Error(), "No help topic for") {
|
||||
t.Fatalf("expected an unknown help topic error, but got: %v", exitErr.Error())
|
||||
}
|
||||
|
||||
if exitErr.exitCode != 3 {
|
||||
t.Fatalf("expected exit value = 3, got %d instead", exitErr.exitCode)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user