11package cmd
22
3- import "testing"
3+ import (
4+ "errors"
5+ "strings"
6+ "testing"
7+ )
48
59func TestCleanVersion (t * testing.T ) {
610 tests := []struct {
@@ -25,3 +29,95 @@ func TestCleanVersion(t *testing.T) {
2529 })
2630 }
2731}
32+
33+ func TestFormatExecuteError (t * testing.T ) {
34+ tests := []struct {
35+ name string
36+ err error
37+ wantEmpty bool
38+ wantSubstr []string
39+ }{
40+ {
41+ name : "nil error" ,
42+ err : nil ,
43+ wantEmpty : true ,
44+ },
45+ {
46+ name : "unknown command" ,
47+ err : errors .New (`unknown command "foo" for "archcore"` ),
48+ wantSubstr : []string {`unknown command "foo"` , "--help" , "available commands" },
49+ },
50+ {
51+ name : "unknown command with suggestion" ,
52+ err : errors .New ("unknown command \" ini\" for \" archcore\" \n \n Did you mean this?\n \t init" ),
53+ wantSubstr : []string {`unknown command "ini"` , "Did you mean this?" , "init" , "--help" },
54+ },
55+ {
56+ name : "unknown flag" ,
57+ err : errors .New ("unknown flag: --bogus" ),
58+ wantSubstr : []string {"unknown flag: --bogus" , "--help" , "available options" },
59+ },
60+ {
61+ name : "unknown shorthand flag" ,
62+ err : errors .New (`unknown shorthand flag: 'x' in -x` ),
63+ wantSubstr : []string {"unknown shorthand flag" , "--help" , "available options" },
64+ },
65+ {
66+ name : "unrelated error" ,
67+ err : errors .New ("something else went wrong" ),
68+ wantEmpty : true ,
69+ },
70+ }
71+ for _ , tt := range tests {
72+ t .Run (tt .name , func (t * testing.T ) {
73+ got := FormatExecuteError (tt .err )
74+ if tt .wantEmpty {
75+ if got != "" {
76+ t .Errorf ("expected empty string, got %q" , got )
77+ }
78+ return
79+ }
80+ for _ , sub := range tt .wantSubstr {
81+ if ! strings .Contains (got , sub ) {
82+ t .Errorf ("output missing %q\n got: %s" , sub , got )
83+ }
84+ }
85+ })
86+ }
87+ }
88+
89+ func TestUnknownCommandOutput (t * testing.T ) {
90+ root := NewRootCmd ("test" )
91+ root .SetArgs ([]string {"foo" })
92+
93+ err := root .ExecuteContext (t .Context ())
94+ if err == nil {
95+ t .Fatal ("expected error for unknown command" )
96+ }
97+
98+ msg := FormatExecuteError (err )
99+ if ! strings .Contains (msg , `"foo"` ) {
100+ t .Errorf ("output should mention the unknown command, got: %s" , msg )
101+ }
102+ if ! strings .Contains (msg , "--help" ) {
103+ t .Errorf ("output should mention --help, got: %s" , msg )
104+ }
105+ }
106+
107+ func TestUnknownFlagOutput (t * testing.T ) {
108+ root := NewRootCmd ("test" )
109+ root .SetArgs ([]string {"--bogus" })
110+
111+ err := root .ExecuteContext (t .Context ())
112+ if err == nil {
113+ t .Fatal ("expected error for unknown flag" )
114+ }
115+
116+ msg := FormatExecuteError (err )
117+ if ! strings .Contains (msg , "--bogus" ) {
118+ t .Errorf ("output should mention the unknown flag, got: %s" , msg )
119+ }
120+ if ! strings .Contains (msg , "--help" ) {
121+ t .Errorf ("output should mention --help, got: %s" , msg )
122+ }
123+ }
0 commit comments