@@ -17,7 +17,6 @@ package cobra
17
17
import (
18
18
"bytes"
19
19
"context"
20
- "errors"
21
20
"fmt"
22
21
"io"
23
22
"os"
@@ -224,7 +223,8 @@ func TestSubcommandExecuteMissingSubcommand(t *testing.T) {
224
223
}
225
224
226
225
func TestSubcommandExecuteMissingSubcommandWithErrorOnUnknownSubcommand (t * testing.T ) {
227
- rootCmd := & Command {Use : "root" , Run : emptyRun }
226
+ const rootName = "root"
227
+ rootCmd := & Command {Use : rootName , Run : emptyRun }
228
228
const childName = "child"
229
229
const grandchildName = "grandchild"
230
230
EnableErrorOnUnknownSubcommand = true
@@ -236,10 +236,10 @@ func TestSubcommandExecuteMissingSubcommandWithErrorOnUnknownSubcommand(t *testi
236
236
237
237
// test existing command
238
238
c , output , err := executeCommandC (rootCmd , childName )
239
- if ! strings .HasPrefix (output , "Error:" ) {
239
+ if strings .HasPrefix (output , "Error:" ) {
240
240
t .Errorf ("Unexpected output: %v" , output )
241
241
}
242
- if ! errors . Is ( err , ErrUnknownSubcommand ) {
242
+ if err != nil {
243
243
t .Errorf ("Unexpected error: %v" , err )
244
244
}
245
245
if c .Name () != childName {
@@ -258,12 +258,30 @@ func TestSubcommandExecuteMissingSubcommandWithErrorOnUnknownSubcommand(t *testi
258
258
t .Errorf (`invalid command returned from ExecuteC: expected "child"', got: %q` , c .Name ())
259
259
}
260
260
261
- // now test a command which does not exist, we expect an error because of the ErrorOnUnknownSubcommand flag
262
- c , output , err = executeCommandC (rootCmd , childName , "unknownChild" )
261
+ // test a child command which does not exist, we expect an error because of the ErrorOnUnknownSubcommand flag
262
+ c , output , err = executeCommandC (rootCmd , "unknownChild" )
263
+ if ! strings .HasPrefix (output , "Error:" ) {
264
+ t .Errorf ("Unexpected output: %v" , output )
265
+ }
266
+ if err == nil {
267
+ t .Error ("Expected error" )
268
+ }
269
+ if err != nil && ! strings .HasPrefix (err .Error (), "unknown command" ) {
270
+ t .Errorf ("Unexpected error: %v" , err )
271
+ }
272
+ if c .Name () != rootName {
273
+ t .Errorf (`invalid command returned from ExecuteC: expected "child"', got: %q` , c .Name ())
274
+ }
275
+
276
+ // test a grandchild command which does not exist, we expect an error because of the ErrorOnUnknownSubcommand flag
277
+ c , output , err = executeCommandC (rootCmd , childName , "unknownGrandChild" )
263
278
if ! strings .HasPrefix (output , "Error:" ) {
264
279
t .Errorf ("Unexpected output: %v" , output )
265
280
}
266
- if ! errors .Is (err , ErrUnknownSubcommand ) {
281
+ if err == nil {
282
+ t .Error ("Expected error" )
283
+ }
284
+ if err != nil && ! strings .HasPrefix (err .Error (), "unknown command" ) {
267
285
t .Errorf ("Unexpected error: %v" , err )
268
286
}
269
287
if c .Name () != childName {
0 commit comments