Skip to content
Myr

command_test.go

This file

Path

command_test.go

2,345 lines · 60.9 KiB · Go

Last changed by

add missing license headers (#1809)Unai Martinez-Corralbefore adoption6d978a9

History of this file

Take it

The walk stopped after 200 commits: lines older than 090d94f point at it.

add missing license headers (#1809)Unai Martinez-Corralbefore adoption6d978a9

lines 1–14why, one step back
1// Copyright 2013-2022 The Cobra Authors
2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 15–20why, one step back
15package cobra
1617import (18 "bytes"19 "context"20 "fmt"

Fix stderr printing functions (#894)Alessio Tregliabefore adoption40d34bc

line 21why, one step back
21 "io/ioutil"

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 22–58why, one step back
22 "os"
23 "reflect"24 "strings"25 "testing"2627 "github.com/spf13/pflag"28)2930func emptyRun(*Command, []string) {}3132func executeCommand(root *Command, args ...string) (output string, err error) {33 _, output, err = executeCommandC(root, args...)34 return output, err35}3637func executeCommandWithContext(ctx context.Context, root *Command, args ...string) (output string, err error) {38 buf := new(bytes.Buffer)39 root.SetOut(buf)40 root.SetErr(buf)41 root.SetArgs(args)4243 err = root.ExecuteContext(ctx)4445 return buf.String(), err46}4748func executeCommandC(root *Command, args ...string) (c *Command, output string, err error) {49 buf := new(bytes.Buffer)50 root.SetOut(buf)51 root.SetErr(buf)52 root.SetArgs(args)5354 c, err = root.ExecuteC()5556 return c, buf.String(), err57}58

Pass context to completion (#1265)Lukas Malkmusbefore adoption6d00909

lines 59–69why, one step back
59func executeCommandWithContextC(ctx context.Context, root *Command, args ...string) (c *Command, output string, err error) {
60 buf := new(bytes.Buffer)61 root.SetOut(buf)62 root.SetErr(buf)63 root.SetArgs(args)6465 c, err = root.ExecuteContextC(ctx)6667 return c, buf.String(), err68}69

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 70–85why, one step back
70func resetCommandLineFlagSet() {
71 pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)72}7374func checkStringContains(t *testing.T, got, expected string) {75 if !strings.Contains(got, expected) {76 t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got)77 }78}7980func checkStringOmits(t *testing.T, got, expected string) {81 if strings.Contains(got, expected) {82 t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got)83 }84}85

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 86–87why, one step back
86const onetwo = "one two"
87

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 88–107why, one step back
88func TestSingleCommand(t *testing.T) {
89 var rootCmdArgs []string90 rootCmd := &Command{91 Use: "root",92 Args: ExactArgs(2),93 Run: func(_ *Command, args []string) { rootCmdArgs = args },94 }95 aCmd := &Command{Use: "a", Args: NoArgs, Run: emptyRun}96 bCmd := &Command{Use: "b", Args: NoArgs, Run: emptyRun}97 rootCmd.AddCommand(aCmd, bCmd)9899 output, err := executeCommand(rootCmd, "one", "two")100 if output != "" {101 t.Errorf("Unexpected output: %v", output)102 }103 if err != nil {104 t.Errorf("Unexpected error: %v", err)105 }106107 got := strings.Join(rootCmdArgs, " ")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 108–109why, one step back
108 if got != onetwo {
109 t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 110–132why, one step back
110 }
111}112113func TestChildCommand(t *testing.T) {114 var child1CmdArgs []string115 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}116 child1Cmd := &Command{117 Use: "child1",118 Args: ExactArgs(2),119 Run: func(_ *Command, args []string) { child1CmdArgs = args },120 }121 child2Cmd := &Command{Use: "child2", Args: NoArgs, Run: emptyRun}122 rootCmd.AddCommand(child1Cmd, child2Cmd)123124 output, err := executeCommand(rootCmd, "child1", "one", "two")125 if output != "" {126 t.Errorf("Unexpected output: %v", output)127 }128 if err != nil {129 t.Errorf("Unexpected error: %v", err)130 }131132 got := strings.Join(child1CmdArgs, " ")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 133–134why, one step back
133 if got != onetwo {
134 t.Errorf("child1CmdArgs expected: %q, got: %q", onetwo, got)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 135–172why, one step back
135 }
136}137138func TestCallCommandWithoutSubcommands(t *testing.T) {139 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}140 _, err := executeCommand(rootCmd)141 if err != nil {142 t.Errorf("Calling command without subcommands should not have error: %v", err)143 }144}145146func TestRootExecuteUnknownCommand(t *testing.T) {147 rootCmd := &Command{Use: "root", Run: emptyRun}148 rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})149150 output, _ := executeCommand(rootCmd, "unknown")151152 expected := "Error: unknown command \"unknown\" for \"root\"\nRun 'root --help' for usage.\n"153154 if output != expected {155 t.Errorf("Expected:\n %q\nGot:\n %q\n", expected, output)156 }157}158159func TestSubcommandExecuteC(t *testing.T) {160 rootCmd := &Command{Use: "root", Run: emptyRun}161 childCmd := &Command{Use: "child", Run: emptyRun}162 rootCmd.AddCommand(childCmd)163164 c, output, err := executeCommandC(rootCmd, "child")165 if output != "" {166 t.Errorf("Unexpected output: %v", output)167 }168 if err != nil {169 t.Errorf("Unexpected error: %v", err)170 }171172 if c.Name() != "child" {

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

line 173why, one step back
173 t.Errorf(`invalid command returned from ExecuteC: expected "child"', got: %q`, c.Name())

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 174–201why, one step back
174 }
175}176177func TestExecuteContext(t *testing.T) {178 ctx := context.TODO()179180 ctxRun := func(cmd *Command, args []string) {181 if cmd.Context() != ctx {182 t.Errorf("Command %q must have context when called with ExecuteContext", cmd.Use)183 }184 }185186 rootCmd := &Command{Use: "root", Run: ctxRun, PreRun: ctxRun}187 childCmd := &Command{Use: "child", Run: ctxRun, PreRun: ctxRun}188 granchildCmd := &Command{Use: "grandchild", Run: ctxRun, PreRun: ctxRun}189190 childCmd.AddCommand(granchildCmd)191 rootCmd.AddCommand(childCmd)192193 if _, err := executeCommandWithContext(ctx, rootCmd, ""); err != nil {194 t.Errorf("Root command must not fail: %+v", err)195 }196197 if _, err := executeCommandWithContext(ctx, rootCmd, "child"); err != nil {198 t.Errorf("Subcommand must not fail: %+v", err)199 }200201 if _, err := executeCommandWithContext(ctx, rootCmd, "child", "grandchild"); err != nil {

Pass context to completion (#1265)Lukas Malkmusbefore adoption6d00909

lines 202–230why, one step back
202 t.Errorf("Command child must not fail: %+v", err)
203 }204}205206func TestExecuteContextC(t *testing.T) {207 ctx := context.TODO()208209 ctxRun := func(cmd *Command, args []string) {210 if cmd.Context() != ctx {211 t.Errorf("Command %q must have context when called with ExecuteContext", cmd.Use)212 }213 }214215 rootCmd := &Command{Use: "root", Run: ctxRun, PreRun: ctxRun}216 childCmd := &Command{Use: "child", Run: ctxRun, PreRun: ctxRun}217 granchildCmd := &Command{Use: "grandchild", Run: ctxRun, PreRun: ctxRun}218219 childCmd.AddCommand(granchildCmd)220 rootCmd.AddCommand(childCmd)221222 if _, _, err := executeCommandWithContextC(ctx, rootCmd, ""); err != nil {223 t.Errorf("Root command must not fail: %+v", err)224 }225226 if _, _, err := executeCommandWithContextC(ctx, rootCmd, "child"); err != nil {227 t.Errorf("Subcommand must not fail: %+v", err)228 }229230 if _, _, err := executeCommandWithContextC(ctx, rootCmd, "child", "grandchild"); err != nil {

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 231–299why, one step back
231 t.Errorf("Command child must not fail: %+v", err)
232 }233}234235func TestExecute_NoContext(t *testing.T) {236 run := func(cmd *Command, args []string) {237 if cmd.Context() != context.Background() {238 t.Errorf("Command %s must have background context", cmd.Use)239 }240 }241242 rootCmd := &Command{Use: "root", Run: run, PreRun: run}243 childCmd := &Command{Use: "child", Run: run, PreRun: run}244 granchildCmd := &Command{Use: "grandchild", Run: run, PreRun: run}245246 childCmd.AddCommand(granchildCmd)247 rootCmd.AddCommand(childCmd)248249 if _, err := executeCommand(rootCmd, ""); err != nil {250 t.Errorf("Root command must not fail: %+v", err)251 }252253 if _, err := executeCommand(rootCmd, "child"); err != nil {254 t.Errorf("Subcommand must not fail: %+v", err)255 }256257 if _, err := executeCommand(rootCmd, "child", "grandchild"); err != nil {258 t.Errorf("Command child must not fail: %+v", err)259 }260}261262func TestRootUnknownCommandSilenced(t *testing.T) {263 rootCmd := &Command{Use: "root", Run: emptyRun}264 rootCmd.SilenceErrors = true265 rootCmd.SilenceUsage = true266 rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})267268 output, _ := executeCommand(rootCmd, "unknown")269 if output != "" {270 t.Errorf("Expected blank output, because of silenced usage.\nGot:\n %q\n", output)271 }272}273274func TestCommandAlias(t *testing.T) {275 var timesCmdArgs []string276 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}277 echoCmd := &Command{278 Use: "echo",279 Aliases: []string{"say", "tell"},280 Args: NoArgs,281 Run: emptyRun,282 }283 timesCmd := &Command{284 Use: "times",285 Args: ExactArgs(2),286 Run: func(_ *Command, args []string) { timesCmdArgs = args },287 }288 echoCmd.AddCommand(timesCmd)289 rootCmd.AddCommand(echoCmd)290291 output, err := executeCommand(rootCmd, "tell", "times", "one", "two")292 if output != "" {293 t.Errorf("Unexpected output: %v", output)294 }295 if err != nil {296 t.Errorf("Unexpected error: %v", err)297 }298299 got := strings.Join(timesCmdArgs, " ")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 300–301why, one step back
300 if got != onetwo {
301 t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 302–326why, one step back
302 }
303}304305func TestEnablePrefixMatching(t *testing.T) {306 EnablePrefixMatching = true307308 var aCmdArgs []string309 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}310 aCmd := &Command{311 Use: "aCmd",312 Args: ExactArgs(2),313 Run: func(_ *Command, args []string) { aCmdArgs = args },314 }315 bCmd := &Command{Use: "bCmd", Args: NoArgs, Run: emptyRun}316 rootCmd.AddCommand(aCmd, bCmd)317318 output, err := executeCommand(rootCmd, "a", "one", "two")319 if output != "" {320 t.Errorf("Unexpected output: %v", output)321 }322 if err != nil {323 t.Errorf("Unexpected error: %v", err)324 }325326 got := strings.Join(aCmdArgs, " ")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 327–328why, one step back
327 if got != onetwo {
328 t.Errorf("aCmdArgs expected: %q, got: %q", onetwo, got)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 329–330why, one step back
329 }
330

Support for case-insensitive command names (#1802)Yuval Goldbergbefore adoptiond689184

line 331why, one step back
331 EnablePrefixMatching = defaultPrefixMatching

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 332–361why, one step back
332}
333334func TestAliasPrefixMatching(t *testing.T) {335 EnablePrefixMatching = true336337 var timesCmdArgs []string338 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}339 echoCmd := &Command{340 Use: "echo",341 Aliases: []string{"say", "tell"},342 Args: NoArgs,343 Run: emptyRun,344 }345 timesCmd := &Command{346 Use: "times",347 Args: ExactArgs(2),348 Run: func(_ *Command, args []string) { timesCmdArgs = args },349 }350 echoCmd.AddCommand(timesCmd)351 rootCmd.AddCommand(echoCmd)352353 output, err := executeCommand(rootCmd, "sa", "times", "one", "two")354 if output != "" {355 t.Errorf("Unexpected output: %v", output)356 }357 if err != nil {358 t.Errorf("Unexpected error: %v", err)359 }360361 got := strings.Join(timesCmdArgs, " ")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 362–363why, one step back
362 if got != onetwo {
363 t.Errorf("timesCmdArgs expected: %v, got: %v", onetwo, got)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 364–365why, one step back
364 }
365

Support for case-insensitive command names (#1802)Yuval Goldbergbefore adoptiond689184

line 366why, one step back
366 EnablePrefixMatching = defaultPrefixMatching

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 367–391why, one step back
367}
368369// TestChildSameName checks the correct behaviour of cobra in cases,370// when an application with name "foo" and with subcommand "foo"371// is executed with args "foo foo".372func TestChildSameName(t *testing.T) {373 var fooCmdArgs []string374 rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun}375 fooCmd := &Command{376 Use: "foo",377 Args: ExactArgs(2),378 Run: func(_ *Command, args []string) { fooCmdArgs = args },379 }380 barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun}381 rootCmd.AddCommand(fooCmd, barCmd)382383 output, err := executeCommand(rootCmd, "foo", "one", "two")384 if output != "" {385 t.Errorf("Unexpected output: %v", output)386 }387 if err != nil {388 t.Errorf("Unexpected error: %v", err)389 }390391 got := strings.Join(fooCmdArgs, " ")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 392–393why, one step back
392 if got != onetwo {
393 t.Errorf("fooCmdArgs expected: %v, got: %v", onetwo, got)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 394–420why, one step back
394 }
395}396397// TestGrandChildSameName checks the correct behaviour of cobra in cases,398// when user has a root command and a grand child399// with the same name.400func TestGrandChildSameName(t *testing.T) {401 var fooCmdArgs []string402 rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun}403 barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun}404 fooCmd := &Command{405 Use: "foo",406 Args: ExactArgs(2),407 Run: func(_ *Command, args []string) { fooCmdArgs = args },408 }409 barCmd.AddCommand(fooCmd)410 rootCmd.AddCommand(barCmd)411412 output, err := executeCommand(rootCmd, "bar", "foo", "one", "two")413 if output != "" {414 t.Errorf("Unexpected output: %v", output)415 }416 if err != nil {417 t.Errorf("Unexpected error: %v", err)418 }419420 got := strings.Join(fooCmdArgs, " ")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 421–422why, one step back
421 if got != onetwo {
422 t.Errorf("fooCmdArgs expected: %v, got: %v", onetwo, got)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 423–457why, one step back
423 }
424}425426func TestFlagLong(t *testing.T) {427 var cArgs []string428 c := &Command{429 Use: "c",430 Args: ArbitraryArgs,431 Run: func(_ *Command, args []string) { cArgs = args },432 }433434 var intFlagValue int435 var stringFlagValue string436 c.Flags().IntVar(&intFlagValue, "intf", -1, "")437 c.Flags().StringVar(&stringFlagValue, "sf", "", "")438439 output, err := executeCommand(c, "--intf=7", "--sf=abc", "one", "--", "two")440 if output != "" {441 t.Errorf("Unexpected output: %v", err)442 }443 if err != nil {444 t.Errorf("Unexpected error: %v", err)445 }446447 if c.ArgsLenAtDash() != 1 {448 t.Errorf("Expected ArgsLenAtDash: %v but got %v", 1, c.ArgsLenAtDash())449 }450 if intFlagValue != 7 {451 t.Errorf("Expected intFlagValue: %v, got %v", 7, intFlagValue)452 }453 if stringFlagValue != "abc" {454 t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)455 }456457 got := strings.Join(cArgs, " ")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 458–459why, one step back
458 if got != onetwo {
459 t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 460–491why, one step back
460 }
461}462463func TestFlagShort(t *testing.T) {464 var cArgs []string465 c := &Command{466 Use: "c",467 Args: ArbitraryArgs,468 Run: func(_ *Command, args []string) { cArgs = args },469 }470471 var intFlagValue int472 var stringFlagValue string473 c.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")474 c.Flags().StringVarP(&stringFlagValue, "sf", "s", "", "")475476 output, err := executeCommand(c, "-i", "7", "-sabc", "one", "two")477 if output != "" {478 t.Errorf("Unexpected output: %v", err)479 }480 if err != nil {481 t.Errorf("Unexpected error: %v", err)482 }483484 if intFlagValue != 7 {485 t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)486 }487 if stringFlagValue != "abc" {488 t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)489 }490491 got := strings.Join(cArgs, " ")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 492–493why, one step back
492 if got != onetwo {
493 t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 494–694why, one step back
494 }
495}496497func TestChildFlag(t *testing.T) {498 rootCmd := &Command{Use: "root", Run: emptyRun}499 childCmd := &Command{Use: "child", Run: emptyRun}500 rootCmd.AddCommand(childCmd)501502 var intFlagValue int503 childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")504505 output, err := executeCommand(rootCmd, "child", "-i7")506 if output != "" {507 t.Errorf("Unexpected output: %v", err)508 }509 if err != nil {510 t.Errorf("Unexpected error: %v", err)511 }512513 if intFlagValue != 7 {514 t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)515 }516}517518func TestChildFlagWithParentLocalFlag(t *testing.T) {519 rootCmd := &Command{Use: "root", Run: emptyRun}520 childCmd := &Command{Use: "child", Run: emptyRun}521 rootCmd.AddCommand(childCmd)522523 var intFlagValue int524 rootCmd.Flags().StringP("sf", "s", "", "")525 childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")526527 _, err := executeCommand(rootCmd, "child", "-i7", "-sabc")528 if err == nil {529 t.Errorf("Invalid flag should generate error")530 }531532 checkStringContains(t, err.Error(), "unknown shorthand")533534 if intFlagValue != 7 {535 t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)536 }537}538539func TestFlagInvalidInput(t *testing.T) {540 rootCmd := &Command{Use: "root", Run: emptyRun}541 rootCmd.Flags().IntP("intf", "i", -1, "")542543 _, err := executeCommand(rootCmd, "-iabc")544 if err == nil {545 t.Errorf("Invalid flag value should generate error")546 }547548 checkStringContains(t, err.Error(), "invalid syntax")549}550551func TestFlagBeforeCommand(t *testing.T) {552 rootCmd := &Command{Use: "root", Run: emptyRun}553 childCmd := &Command{Use: "child", Run: emptyRun}554 rootCmd.AddCommand(childCmd)555556 var flagValue int557 childCmd.Flags().IntVarP(&flagValue, "intf", "i", -1, "")558559 // With short flag.560 _, err := executeCommand(rootCmd, "-i7", "child")561 if err != nil {562 t.Errorf("Unexpected error: %v", err)563 }564 if flagValue != 7 {565 t.Errorf("Expected flag value: %v, got %v", 7, flagValue)566 }567568 // With long flag.569 _, err = executeCommand(rootCmd, "--intf=8", "child")570 if err != nil {571 t.Errorf("Unexpected error: %v", err)572 }573 if flagValue != 8 {574 t.Errorf("Expected flag value: %v, got %v", 9, flagValue)575 }576}577578func TestStripFlags(t *testing.T) {579 tests := []struct {580 input []string581 output []string582 }{583 {584 []string{"foo", "bar"},585 []string{"foo", "bar"},586 },587 {588 []string{"foo", "--str", "-s"},589 []string{"foo"},590 },591 {592 []string{"-s", "foo", "--str", "bar"},593 []string{},594 },595 {596 []string{"-i10", "echo"},597 []string{"echo"},598 },599 {600 []string{"-i=10", "echo"},601 []string{"echo"},602 },603 {604 []string{"--int=100", "echo"},605 []string{"echo"},606 },607 {608 []string{"-ib", "echo", "-sfoo", "baz"},609 []string{"echo", "baz"},610 },611 {612 []string{"-i=baz", "bar", "-i", "foo", "blah"},613 []string{"bar", "blah"},614 },615 {616 []string{"--int=baz", "-sbar", "-i", "foo", "blah"},617 []string{"blah"},618 },619 {620 []string{"--bool", "bar", "-i", "foo", "blah"},621 []string{"bar", "blah"},622 },623 {624 []string{"-b", "bar", "-i", "foo", "blah"},625 []string{"bar", "blah"},626 },627 {628 []string{"--persist", "bar"},629 []string{"bar"},630 },631 {632 []string{"-p", "bar"},633 []string{"bar"},634 },635 }636637 c := &Command{Use: "c", Run: emptyRun}638 c.PersistentFlags().BoolP("persist", "p", false, "")639 c.Flags().IntP("int", "i", -1, "")640 c.Flags().StringP("str", "s", "", "")641 c.Flags().BoolP("bool", "b", false, "")642643 for i, test := range tests {644 got := stripFlags(test.input, c)645 if !reflect.DeepEqual(test.output, got) {646 t.Errorf("(%v) Expected: %v, got: %v", i, test.output, got)647 }648 }649}650651func TestDisableFlagParsing(t *testing.T) {652 var cArgs []string653 c := &Command{654 Use: "c",655 DisableFlagParsing: true,656 Run: func(_ *Command, args []string) {657 cArgs = args658 },659 }660661 args := []string{"cmd", "-v", "-race", "-file", "foo.go"}662 output, err := executeCommand(c, args...)663 if output != "" {664 t.Errorf("Unexpected output: %v", output)665 }666 if err != nil {667 t.Errorf("Unexpected error: %v", err)668 }669670 if !reflect.DeepEqual(args, cArgs) {671 t.Errorf("Expected: %v, got: %v", args, cArgs)672 }673}674675func TestPersistentFlagsOnSameCommand(t *testing.T) {676 var rootCmdArgs []string677 rootCmd := &Command{678 Use: "root",679 Args: ArbitraryArgs,680 Run: func(_ *Command, args []string) { rootCmdArgs = args },681 }682683 var flagValue int684 rootCmd.PersistentFlags().IntVarP(&flagValue, "intf", "i", -1, "")685686 output, err := executeCommand(rootCmd, "-i7", "one", "two")687 if output != "" {688 t.Errorf("Unexpected output: %v", output)689 }690 if err != nil {691 t.Errorf("Unexpected error: %v", err)692 }693694 got := strings.Join(rootCmdArgs, " ")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 695–696why, one step back
695 if got != onetwo {
696 t.Errorf("rootCmdArgs expected: %q, got %q", onetwo, got)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 697–723why, one step back
697 }
698 if flagValue != 7 {699 t.Errorf("flagValue expected: %v, got %v", 7, flagValue)700 }701}702703// TestEmptyInputs checks,704// if flags correctly parsed with blank strings in args.705func TestEmptyInputs(t *testing.T) {706 c := &Command{Use: "c", Run: emptyRun}707708 var flagValue int709 c.Flags().IntVarP(&flagValue, "intf", "i", -1, "")710711 output, err := executeCommand(c, "", "-i7", "")712 if output != "" {713 t.Errorf("Unexpected output: %v", output)714 }715 if err != nil {716 t.Errorf("Unexpected error: %v", err)717 }718719 if flagValue != 7 {720 t.Errorf("flagValue expected: %v, got %v", 7, flagValue)721 }722}723

fix: show flags that shadow parent persistent flag in child help (#1776)Brian Pursleybefore adoption22b6179

line 724why, one step back
724func TestChildFlagShadowsParentPersistentFlag(t *testing.T) {

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 725–745why, one step back
725 parent := &Command{Use: "parent", Run: emptyRun}
726 child := &Command{Use: "child", Run: emptyRun}727728 parent.PersistentFlags().Bool("boolf", false, "")729 parent.PersistentFlags().Int("intf", -1, "")730 child.Flags().String("strf", "", "")731 child.Flags().Int("intf", -1, "")732733 parent.AddCommand(child)734735 childInherited := child.InheritedFlags()736 childLocal := child.LocalFlags()737738 if childLocal.Lookup("strf") == nil {739 t.Error(`LocalFlags expected to contain "strf", got "nil"`)740 }741 if childInherited.Lookup("boolf") == nil {742 t.Error(`InheritedFlags expected to contain "boolf", got "nil"`)743 }744745 if childInherited.Lookup("intf") != nil {

fix: show flags that shadow parent persistent flag in child help (#1776)Brian Pursleybefore adoption22b6179

line 746why, one step back
746 t.Errorf(`InheritedFlags should not contain shadowed flag "intf"`)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 747–776why, one step back
747 }
748 if childLocal.Lookup("intf") == nil {749 t.Error(`LocalFlags expected to contain "intf", got "nil"`)750 }751}752753func TestPersistentFlagsOnChild(t *testing.T) {754 var childCmdArgs []string755 rootCmd := &Command{Use: "root", Run: emptyRun}756 childCmd := &Command{757 Use: "child",758 Args: ArbitraryArgs,759 Run: func(_ *Command, args []string) { childCmdArgs = args },760 }761 rootCmd.AddCommand(childCmd)762763 var parentFlagValue int764 var childFlagValue int765 rootCmd.PersistentFlags().IntVarP(&parentFlagValue, "parentf", "p", -1, "")766 childCmd.Flags().IntVarP(&childFlagValue, "childf", "c", -1, "")767768 output, err := executeCommand(rootCmd, "child", "-c7", "-p8", "one", "two")769 if output != "" {770 t.Errorf("Unexpected output: %v", output)771 }772 if err != nil {773 t.Errorf("Unexpected error: %v", err)774 }775776 got := strings.Join(childCmdArgs, " ")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 777–778why, one step back
777 if got != onetwo {
778 t.Errorf("rootCmdArgs expected: %q, got: %q", onetwo, got)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 779–790why, one step back
779 }
780 if parentFlagValue != 8 {781 t.Errorf("parentFlagValue expected: %v, got %v", 8, parentFlagValue)782 }783 if childFlagValue != 7 {784 t.Errorf("childFlagValue expected: %v, got %v", 7, childFlagValue)785 }786}787788func TestRequiredFlags(t *testing.T) {789 c := &Command{Use: "c", Run: emptyRun}790 c.Flags().String("foo1", "", "")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

line 791why, one step back
791 assertNoErr(t, c.MarkFlagRequired("foo1"))

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

line 792why, one step back
792 c.Flags().String("foo2", "", "")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

line 793why, one step back
793 assertNoErr(t, c.MarkFlagRequired("foo2"))

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 794–808why, one step back
794 c.Flags().String("bar", "", "")
795796 expected := fmt.Sprintf("required flag(s) %q, %q not set", "foo1", "foo2")797798 _, err := executeCommand(c)799 got := err.Error()800801 if got != expected {802 t.Errorf("Expected error: %q, got: %q", expected, got)803 }804}805806func TestPersistentRequiredFlags(t *testing.T) {807 parent := &Command{Use: "parent", Run: emptyRun}808 parent.PersistentFlags().String("foo1", "", "")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

line 809why, one step back
809 assertNoErr(t, parent.MarkPersistentFlagRequired("foo1"))

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

line 810why, one step back
810 parent.PersistentFlags().String("foo2", "", "")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

line 811why, one step back
811 assertNoErr(t, parent.MarkPersistentFlagRequired("foo2"))

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 812–815why, one step back
812 parent.Flags().String("foo3", "", "")
813814 child := &Command{Use: "child", Run: emptyRun}815 child.Flags().String("bar1", "", "")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

line 816why, one step back
816 assertNoErr(t, child.MarkFlagRequired("bar1"))

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

line 817why, one step back
817 child.Flags().String("bar2", "", "")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

line 818why, one step back
818 assertNoErr(t, child.MarkFlagRequired("bar2"))

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 819–830why, one step back
819 child.Flags().String("bar3", "", "")
820821 parent.AddCommand(child)822823 expected := fmt.Sprintf("required flag(s) %q, %q, %q, %q not set", "bar1", "bar2", "foo1", "foo2")824825 _, err := executeCommand(parent, "child")826 if err.Error() != expected {827 t.Errorf("Expected %q, got %q", expected, err.Error())828 }829}830

Ignore required flags when DisableFlagParsing (#1095)Marc Khouzambefore adoption5155946

lines 831–837why, one step back
831func TestPersistentRequiredFlagsWithDisableFlagParsing(t *testing.T) {
832 // Make sure a required persistent flag does not break833 // commands that disable flag parsing834835 parent := &Command{Use: "parent", Run: emptyRun}836 parent.PersistentFlags().Bool("foo", false, "")837 flag := parent.PersistentFlags().Lookup("foo")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

line 838why, one step back
838 assertNoErr(t, parent.MarkPersistentFlagRequired("foo"))

Ignore required flags when DisableFlagParsing (#1095)Marc Khouzambefore adoption5155946

lines 839–861why, one step back
839
840 child := &Command{Use: "child", Run: emptyRun}841 child.DisableFlagParsing = true842843 parent.AddCommand(child)844845 if _, err := executeCommand(parent, "--foo", "child"); err != nil {846 t.Errorf("Unexpected error: %v", err)847 }848849 // Reset the flag or else it will remember the state from the previous command850 flag.Changed = false851 if _, err := executeCommand(parent, "child", "--foo"); err != nil {852 t.Errorf("Unexpected error: %v", err)853 }854855 // Reset the flag or else it will remember the state from the previous command856 flag.Changed = false857 if _, err := executeCommand(parent, "child"); err != nil {858 t.Errorf("Unexpected error: %v", err)859 }860}861

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 862–898why, one step back
862func TestInitHelpFlagMergesFlags(t *testing.T) {
863 usage := "custom flag"864 rootCmd := &Command{Use: "root"}865 rootCmd.PersistentFlags().Bool("help", false, "custom flag")866 childCmd := &Command{Use: "child"}867 rootCmd.AddCommand(childCmd)868869 childCmd.InitDefaultHelpFlag()870 got := childCmd.Flags().Lookup("help").Usage871 if got != usage {872 t.Errorf("Expected the help flag from the root command with usage: %v\nGot the default with usage: %v", usage, got)873 }874}875876func TestHelpCommandExecuted(t *testing.T) {877 rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}878 rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})879880 output, err := executeCommand(rootCmd, "help")881 if err != nil {882 t.Errorf("Unexpected error: %v", err)883 }884885 checkStringContains(t, output, rootCmd.Long)886}887888func TestHelpCommandExecutedOnChild(t *testing.T) {889 rootCmd := &Command{Use: "root", Run: emptyRun}890 childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun}891 rootCmd.AddCommand(childCmd)892893 output, err := executeCommand(rootCmd, "help", "child")894 if err != nil {895 t.Errorf("Unexpected error: %v", err)896 }897898 checkStringContains(t, output, childCmd.Long)

fix: show flags that shadow parent persistent flag in child help (#1776)Brian Pursleybefore adoption22b6179

lines 899–930why, one step back
899}
900901func TestHelpCommandExecutedOnChildWithFlagThatShadowsParentFlag(t *testing.T) {902 parent := &Command{Use: "parent", Run: emptyRun}903 child := &Command{Use: "child", Run: emptyRun}904 parent.AddCommand(child)905906 parent.PersistentFlags().Bool("foo", false, "parent foo usage")907 parent.PersistentFlags().Bool("bar", false, "parent bar usage")908 child.Flags().Bool("foo", false, "child foo usage") // This shadows parent's foo flag909 child.Flags().Bool("baz", false, "child baz usage")910911 got, err := executeCommand(parent, "help", "child")912 if err != nil {913 t.Errorf("Unexpected error: %v", err)914 }915916 expected := `Usage:917 parent child [flags]918919Flags:920 --baz child baz usage921 --foo child foo usage922 -h, --help help for child923924Global Flags:925 --bar parent bar usage926`927928 if got != expected {929 t.Errorf("Help text mismatch.\nExpected:\n%s\n\nGot:\n%s\n", expected, got)930 }

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 931–1279why, one step back
931}
932933func TestSetHelpCommand(t *testing.T) {934 c := &Command{Use: "c", Run: emptyRun}935 c.AddCommand(&Command{Use: "empty", Run: emptyRun})936937 expected := "WORKS"938 c.SetHelpCommand(&Command{939 Use: "help [command]",940 Short: "Help about any command",941 Long: `Help provides help for any command in the application.942 Simply type ` + c.Name() + ` help [path to command] for full details.`,943 Run: func(c *Command, _ []string) { c.Print(expected) },944 })945946 got, err := executeCommand(c, "help")947 if err != nil {948 t.Errorf("Unexpected error: %v", err)949 }950951 if got != expected {952 t.Errorf("Expected to contain %q, got %q", expected, got)953 }954}955956func TestHelpFlagExecuted(t *testing.T) {957 rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}958959 output, err := executeCommand(rootCmd, "--help")960 if err != nil {961 t.Errorf("Unexpected error: %v", err)962 }963964 checkStringContains(t, output, rootCmd.Long)965}966967func TestHelpFlagExecutedOnChild(t *testing.T) {968 rootCmd := &Command{Use: "root", Run: emptyRun}969 childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun}970 rootCmd.AddCommand(childCmd)971972 output, err := executeCommand(rootCmd, "child", "--help")973 if err != nil {974 t.Errorf("Unexpected error: %v", err)975 }976977 checkStringContains(t, output, childCmd.Long)978}979980// TestHelpFlagInHelp checks,981// if '--help' flag is shown in help for child (executing `parent help child`),982// that has no other flags.983// Related to https://github.com/spf13/cobra/issues/302.984func TestHelpFlagInHelp(t *testing.T) {985 parentCmd := &Command{Use: "parent", Run: func(*Command, []string) {}}986987 childCmd := &Command{Use: "child", Run: func(*Command, []string) {}}988 parentCmd.AddCommand(childCmd)989990 output, err := executeCommand(parentCmd, "help", "child")991 if err != nil {992 t.Errorf("Unexpected error: %v", err)993 }994995 checkStringContains(t, output, "[flags]")996}997998func TestFlagsInUsage(t *testing.T) {999 rootCmd := &Command{Use: "root", Args: NoArgs, Run: func(*Command, []string) {}}1000 output, err := executeCommand(rootCmd, "--help")1001 if err != nil {1002 t.Errorf("Unexpected error: %v", err)1003 }10041005 checkStringContains(t, output, "[flags]")1006}10071008func TestHelpExecutedOnNonRunnableChild(t *testing.T) {1009 rootCmd := &Command{Use: "root", Run: emptyRun}1010 childCmd := &Command{Use: "child", Long: "Long description"}1011 rootCmd.AddCommand(childCmd)10121013 output, err := executeCommand(rootCmd, "child")1014 if err != nil {1015 t.Errorf("Unexpected error: %v", err)1016 }10171018 checkStringContains(t, output, childCmd.Long)1019}10201021func TestVersionFlagExecuted(t *testing.T) {1022 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}10231024 output, err := executeCommand(rootCmd, "--version", "arg1")1025 if err != nil {1026 t.Errorf("Unexpected error: %v", err)1027 }10281029 checkStringContains(t, output, "root version 1.0.0")1030}10311032func TestVersionFlagExecutedWithNoName(t *testing.T) {1033 rootCmd := &Command{Version: "1.0.0", Run: emptyRun}10341035 output, err := executeCommand(rootCmd, "--version", "arg1")1036 if err != nil {1037 t.Errorf("Unexpected error: %v", err)1038 }10391040 checkStringContains(t, output, "version 1.0.0")1041}10421043func TestShortAndLongVersionFlagInHelp(t *testing.T) {1044 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}10451046 output, err := executeCommand(rootCmd, "--help")1047 if err != nil {1048 t.Errorf("Unexpected error: %v", err)1049 }10501051 checkStringContains(t, output, "-v, --version")1052}10531054func TestLongVersionFlagOnlyInHelpWhenShortPredefined(t *testing.T) {1055 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}1056 rootCmd.Flags().StringP("foo", "v", "", "not a version flag")10571058 output, err := executeCommand(rootCmd, "--help")1059 if err != nil {1060 t.Errorf("Unexpected error: %v", err)1061 }10621063 checkStringOmits(t, output, "-v, --version")1064 checkStringContains(t, output, "--version")1065}10661067func TestShorthandVersionFlagExecuted(t *testing.T) {1068 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}10691070 output, err := executeCommand(rootCmd, "-v", "arg1")1071 if err != nil {1072 t.Errorf("Unexpected error: %v", err)1073 }10741075 checkStringContains(t, output, "root version 1.0.0")1076}10771078func TestVersionTemplate(t *testing.T) {1079 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}1080 rootCmd.SetVersionTemplate(`customized version: {{.Version}}`)10811082 output, err := executeCommand(rootCmd, "--version", "arg1")1083 if err != nil {1084 t.Errorf("Unexpected error: %v", err)1085 }10861087 checkStringContains(t, output, "customized version: 1.0.0")1088}10891090func TestShorthandVersionTemplate(t *testing.T) {1091 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}1092 rootCmd.SetVersionTemplate(`customized version: {{.Version}}`)10931094 output, err := executeCommand(rootCmd, "-v", "arg1")1095 if err != nil {1096 t.Errorf("Unexpected error: %v", err)1097 }10981099 checkStringContains(t, output, "customized version: 1.0.0")1100}11011102func TestVersionFlagExecutedOnSubcommand(t *testing.T) {1103 rootCmd := &Command{Use: "root", Version: "1.0.0"}1104 rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})11051106 output, err := executeCommand(rootCmd, "--version", "sub")1107 if err != nil {1108 t.Errorf("Unexpected error: %v", err)1109 }11101111 checkStringContains(t, output, "root version 1.0.0")1112}11131114func TestShorthandVersionFlagExecutedOnSubcommand(t *testing.T) {1115 rootCmd := &Command{Use: "root", Version: "1.0.0"}1116 rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})11171118 output, err := executeCommand(rootCmd, "-v", "sub")1119 if err != nil {1120 t.Errorf("Unexpected error: %v", err)1121 }11221123 checkStringContains(t, output, "root version 1.0.0")1124}11251126func TestVersionFlagOnlyAddedToRoot(t *testing.T) {1127 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}1128 rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})11291130 _, err := executeCommand(rootCmd, "sub", "--version")1131 if err == nil {1132 t.Errorf("Expected error")1133 }11341135 checkStringContains(t, err.Error(), "unknown flag: --version")1136}11371138func TestShortVersionFlagOnlyAddedToRoot(t *testing.T) {1139 rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}1140 rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})11411142 _, err := executeCommand(rootCmd, "sub", "-v")1143 if err == nil {1144 t.Errorf("Expected error")1145 }11461147 checkStringContains(t, err.Error(), "unknown shorthand flag: 'v' in -v")1148}11491150func TestVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {1151 rootCmd := &Command{Use: "root", Run: emptyRun}11521153 _, err := executeCommand(rootCmd, "--version")1154 if err == nil {1155 t.Errorf("Expected error")1156 }1157 checkStringContains(t, err.Error(), "unknown flag: --version")1158}11591160func TestShorthandVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {1161 rootCmd := &Command{Use: "root", Run: emptyRun}11621163 _, err := executeCommand(rootCmd, "-v")1164 if err == nil {1165 t.Errorf("Expected error")1166 }1167 checkStringContains(t, err.Error(), "unknown shorthand flag: 'v' in -v")1168}11691170func TestShorthandVersionFlagOnlyAddedIfShorthandNotDefined(t *testing.T) {1171 rootCmd := &Command{Use: "root", Run: emptyRun, Version: "1.2.3"}1172 rootCmd.Flags().StringP("notversion", "v", "", "not a version flag")11731174 _, err := executeCommand(rootCmd, "-v")1175 if err == nil {1176 t.Errorf("Expected error")1177 }1178 check(t, rootCmd.Flags().ShorthandLookup("v").Name, "notversion")1179 checkStringContains(t, err.Error(), "flag needs an argument: 'v' in -v")1180}11811182func TestShorthandVersionFlagOnlyAddedIfVersionNotDefined(t *testing.T) {1183 rootCmd := &Command{Use: "root", Run: emptyRun, Version: "1.2.3"}1184 rootCmd.Flags().Bool("version", false, "a different kind of version flag")11851186 _, err := executeCommand(rootCmd, "-v")1187 if err == nil {1188 t.Errorf("Expected error")1189 }1190 checkStringContains(t, err.Error(), "unknown shorthand flag: 'v' in -v")1191}11921193func TestUsageIsNotPrintedTwice(t *testing.T) {1194 var cmd = &Command{Use: "root"}1195 var sub = &Command{Use: "sub"}1196 cmd.AddCommand(sub)11971198 output, _ := executeCommand(cmd, "")1199 if strings.Count(output, "Usage:") != 1 {1200 t.Error("Usage output is not printed exactly once")1201 }1202}12031204func TestVisitParents(t *testing.T) {1205 c := &Command{Use: "app"}1206 sub := &Command{Use: "sub"}1207 dsub := &Command{Use: "dsub"}1208 sub.AddCommand(dsub)1209 c.AddCommand(sub)12101211 total := 01212 add := func(x *Command) {1213 total++1214 }1215 sub.VisitParents(add)1216 if total != 1 {1217 t.Errorf("Should have visited 1 parent but visited %d", total)1218 }12191220 total = 01221 dsub.VisitParents(add)1222 if total != 2 {1223 t.Errorf("Should have visited 2 parents but visited %d", total)1224 }12251226 total = 01227 c.VisitParents(add)1228 if total != 0 {1229 t.Errorf("Should have visited no parents but visited %d", total)1230 }1231}12321233func TestSuggestions(t *testing.T) {1234 rootCmd := &Command{Use: "root", Run: emptyRun}1235 timesCmd := &Command{1236 Use: "times",1237 SuggestFor: []string{"counts"},1238 Run: emptyRun,1239 }1240 rootCmd.AddCommand(timesCmd)12411242 templateWithSuggestions := "Error: unknown command \"%s\" for \"root\"\n\nDid you mean this?\n\t%s\n\nRun 'root --help' for usage.\n"1243 templateWithoutSuggestions := "Error: unknown command \"%s\" for \"root\"\nRun 'root --help' for usage.\n"12441245 tests := map[string]string{1246 "time": "times",1247 "tiems": "times",1248 "tims": "times",1249 "timeS": "times",1250 "rimes": "times",1251 "ti": "times",1252 "t": "times",1253 "timely": "times",1254 "ri": "",1255 "timezone": "",1256 "foo": "",1257 "counts": "times",1258 }12591260 for typo, suggestion := range tests {1261 for _, suggestionsDisabled := range []bool{true, false} {1262 rootCmd.DisableSuggestions = suggestionsDisabled12631264 var expected string1265 output, _ := executeCommand(rootCmd, typo)12661267 if suggestion == "" || suggestionsDisabled {1268 expected = fmt.Sprintf(templateWithoutSuggestions, typo)1269 } else {1270 expected = fmt.Sprintf(templateWithSuggestions, typo, suggestion)1271 }12721273 if output != expected {1274 t.Errorf("Unexpected response.\nExpected:\n %q\nGot:\n %q\n", expected, output)1275 }1276 }1277 }1278}1279

Support for case-insensitive command names (#1802)Yuval Goldbergbefore adoptiond689184

lines 1280–1386why, one step back
1280func TestCaseInsensitive(t *testing.T) {
1281 rootCmd := &Command{Use: "root", Run: emptyRun}1282 childCmd := &Command{Use: "child", Run: emptyRun, Aliases: []string{"alternative"}}1283 granchildCmd := &Command{Use: "GRANDCHILD", Run: emptyRun, Aliases: []string{"ALIAS"}}12841285 childCmd.AddCommand(granchildCmd)1286 rootCmd.AddCommand(childCmd)12871288 tests := []struct {1289 args []string1290 failWithoutEnabling bool1291 }{1292 {1293 args: []string{"child"},1294 failWithoutEnabling: false,1295 },1296 {1297 args: []string{"CHILD"},1298 failWithoutEnabling: true,1299 },1300 {1301 args: []string{"chILD"},1302 failWithoutEnabling: true,1303 },1304 {1305 args: []string{"CHIld"},1306 failWithoutEnabling: true,1307 },1308 {1309 args: []string{"alternative"},1310 failWithoutEnabling: false,1311 },1312 {1313 args: []string{"ALTERNATIVE"},1314 failWithoutEnabling: true,1315 },1316 {1317 args: []string{"ALTernatIVE"},1318 failWithoutEnabling: true,1319 },1320 {1321 args: []string{"alternatiVE"},1322 failWithoutEnabling: true,1323 },1324 {1325 args: []string{"child", "GRANDCHILD"},1326 failWithoutEnabling: false,1327 },1328 {1329 args: []string{"child", "grandchild"},1330 failWithoutEnabling: true,1331 },1332 {1333 args: []string{"CHIld", "GRANdchild"},1334 failWithoutEnabling: true,1335 },1336 {1337 args: []string{"alternative", "ALIAS"},1338 failWithoutEnabling: false,1339 },1340 {1341 args: []string{"alternative", "alias"},1342 failWithoutEnabling: true,1343 },1344 {1345 args: []string{"CHILD", "alias"},1346 failWithoutEnabling: true,1347 },1348 {1349 args: []string{"CHIld", "aliAS"},1350 failWithoutEnabling: true,1351 },1352 }13531354 for _, test := range tests {1355 for _, enableCaseInsensitivity := range []bool{true, false} {1356 EnableCaseInsensitive = enableCaseInsensitivity13571358 output, err := executeCommand(rootCmd, test.args...)1359 expectedFailure := test.failWithoutEnabling && !enableCaseInsensitivity13601361 if !expectedFailure && output != "" {1362 t.Errorf("Unexpected output: %v", output)1363 }1364 if !expectedFailure && err != nil {1365 t.Errorf("Unexpected error: %v", err)1366 }1367 }1368 }13691370 EnableCaseInsensitive = defaultCaseInsensitive1371}13721373// This test make sure we keep backwards-compatibility with respect1374// to command names case sensitivity behavior.1375func TestCaseSensitivityBackwardCompatibility(t *testing.T) {1376 rootCmd := &Command{Use: "root", Run: emptyRun}1377 childCmd := &Command{Use: "child", Run: emptyRun}13781379 rootCmd.AddCommand(childCmd)1380 _, err := executeCommand(rootCmd, strings.ToUpper(childCmd.Use))1381 if err == nil {1382 t.Error("Expected error on calling a command in upper case while command names are case sensitive. Got nil.")1383 }13841385}1386

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 1387–1482why, one step back
1387func TestRemoveCommand(t *testing.T) {
1388 rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}1389 childCmd := &Command{Use: "child", Run: emptyRun}1390 rootCmd.AddCommand(childCmd)1391 rootCmd.RemoveCommand(childCmd)13921393 _, err := executeCommand(rootCmd, "child")1394 if err == nil {1395 t.Error("Expected error on calling removed command. Got nil.")1396 }1397}13981399func TestReplaceCommandWithRemove(t *testing.T) {1400 childUsed := 01401 rootCmd := &Command{Use: "root", Run: emptyRun}1402 child1Cmd := &Command{1403 Use: "child",1404 Run: func(*Command, []string) { childUsed = 1 },1405 }1406 child2Cmd := &Command{1407 Use: "child",1408 Run: func(*Command, []string) { childUsed = 2 },1409 }1410 rootCmd.AddCommand(child1Cmd)1411 rootCmd.RemoveCommand(child1Cmd)1412 rootCmd.AddCommand(child2Cmd)14131414 output, err := executeCommand(rootCmd, "child")1415 if output != "" {1416 t.Errorf("Unexpected output: %v", output)1417 }1418 if err != nil {1419 t.Errorf("Unexpected error: %v", err)1420 }14211422 if childUsed == 1 {1423 t.Error("Removed command shouldn't be called")1424 }1425 if childUsed != 2 {1426 t.Error("Replacing command should have been called but didn't")1427 }1428}14291430func TestDeprecatedCommand(t *testing.T) {1431 rootCmd := &Command{Use: "root", Run: emptyRun}1432 deprecatedCmd := &Command{1433 Use: "deprecated",1434 Deprecated: "This command is deprecated",1435 Run: emptyRun,1436 }1437 rootCmd.AddCommand(deprecatedCmd)14381439 output, err := executeCommand(rootCmd, "deprecated")1440 if err != nil {1441 t.Errorf("Unexpected error: %v", err)1442 }14431444 checkStringContains(t, output, deprecatedCmd.Deprecated)1445}14461447func TestHooks(t *testing.T) {1448 var (1449 persPreArgs string1450 preArgs string1451 runArgs string1452 postArgs string1453 persPostArgs string1454 )14551456 c := &Command{1457 Use: "c",1458 PersistentPreRun: func(_ *Command, args []string) {1459 persPreArgs = strings.Join(args, " ")1460 },1461 PreRun: func(_ *Command, args []string) {1462 preArgs = strings.Join(args, " ")1463 },1464 Run: func(_ *Command, args []string) {1465 runArgs = strings.Join(args, " ")1466 },1467 PostRun: func(_ *Command, args []string) {1468 postArgs = strings.Join(args, " ")1469 },1470 PersistentPostRun: func(_ *Command, args []string) {1471 persPostArgs = strings.Join(args, " ")1472 },1473 }14741475 output, err := executeCommand(c, "one", "two")1476 if output != "" {1477 t.Errorf("Unexpected output: %v", output)1478 }1479 if err != nil {1480 t.Errorf("Unexpected error: %v", err)1481 }1482

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 1483–1495why, one step back
1483 for _, v := range []struct {
1484 name string1485 got string1486 }{1487 {"persPreArgs", persPreArgs},1488 {"preArgs", preArgs},1489 {"runArgs", runArgs},1490 {"postArgs", postArgs},1491 {"persPostArgs", persPostArgs},1492 } {1493 if v.got != onetwo {1494 t.Errorf("Expected %s %q, got %q", v.name, onetwo, v.got)1495 }

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 1496–1562why, one step back
1496 }
1497}14981499func TestPersistentHooks(t *testing.T) {1500 var (1501 parentPersPreArgs string1502 parentPreArgs string1503 parentRunArgs string1504 parentPostArgs string1505 parentPersPostArgs string1506 )15071508 var (1509 childPersPreArgs string1510 childPreArgs string1511 childRunArgs string1512 childPostArgs string1513 childPersPostArgs string1514 )15151516 parentCmd := &Command{1517 Use: "parent",1518 PersistentPreRun: func(_ *Command, args []string) {1519 parentPersPreArgs = strings.Join(args, " ")1520 },1521 PreRun: func(_ *Command, args []string) {1522 parentPreArgs = strings.Join(args, " ")1523 },1524 Run: func(_ *Command, args []string) {1525 parentRunArgs = strings.Join(args, " ")1526 },1527 PostRun: func(_ *Command, args []string) {1528 parentPostArgs = strings.Join(args, " ")1529 },1530 PersistentPostRun: func(_ *Command, args []string) {1531 parentPersPostArgs = strings.Join(args, " ")1532 },1533 }15341535 childCmd := &Command{1536 Use: "child",1537 PersistentPreRun: func(_ *Command, args []string) {1538 childPersPreArgs = strings.Join(args, " ")1539 },1540 PreRun: func(_ *Command, args []string) {1541 childPreArgs = strings.Join(args, " ")1542 },1543 Run: func(_ *Command, args []string) {1544 childRunArgs = strings.Join(args, " ")1545 },1546 PostRun: func(_ *Command, args []string) {1547 childPostArgs = strings.Join(args, " ")1548 },1549 PersistentPostRun: func(_ *Command, args []string) {1550 childPersPostArgs = strings.Join(args, " ")1551 },1552 }1553 parentCmd.AddCommand(childCmd)15541555 output, err := executeCommand(parentCmd, "child", "one", "two")1556 if output != "" {1557 t.Errorf("Unexpected output: %v", output)1558 }1559 if err != nil {1560 t.Errorf("Unexpected error: %v", err)1561 }1562

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 1563–1566why, one step back
1563 for _, v := range []struct {
1564 name string1565 got string1566 }{

Fix some typos (mostly found by codespell) (#1514)Stefan Weilbefore adoption1854bb5

lines 1567–1568why, one step back
1567 // TODO: currently PersistentPreRun* defined in parent does not
1568 // run if the matching child subcommand has PersistentPreRun.

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 1569–1574why, one step back
1569 // If the behavior changes (https://github.com/spf13/cobra/issues/252)
1570 // this test must be fixed.1571 {"parentPersPreArgs", parentPersPreArgs},1572 {"parentPreArgs", parentPreArgs},1573 {"parentRunArgs", parentRunArgs},1574 {"parentPostArgs", parentPostArgs},

Fix some typos (mostly found by codespell) (#1514)Stefan Weilbefore adoption1854bb5

lines 1575–1576why, one step back
1575 // TODO: currently PersistentPostRun* defined in parent does not
1576 // run if the matching child subcommand has PersistentPostRun.

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 1577–1583why, one step back
1577 // If the behavior changes (https://github.com/spf13/cobra/issues/252)
1578 // this test must be fixed.1579 {"parentPersPostArgs", parentPersPostArgs},1580 } {1581 if v.got != "" {1582 t.Errorf("Expected blank %s, got %q", v.name, v.got)1583 }

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 1584–1585why, one step back
1584 }
1585

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

lines 1586–1598why, one step back
1586 for _, v := range []struct {
1587 name string1588 got string1589 }{1590 {"childPersPreArgs", childPersPreArgs},1591 {"childPreArgs", childPreArgs},1592 {"childRunArgs", childRunArgs},1593 {"childPostArgs", childPostArgs},1594 {"childPersPostArgs", childPersPostArgs},1595 } {1596 if v.got != onetwo {1597 t.Errorf("Expected %s %q, got %q", v.name, onetwo, v.got)1598 }

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 1599–1745why, one step back
1599 }
1600}16011602// Related to https://github.com/spf13/cobra/issues/521.1603func TestGlobalNormFuncPropagation(t *testing.T) {1604 normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1605 return pflag.NormalizedName(name)1606 }16071608 rootCmd := &Command{Use: "root", Run: emptyRun}1609 childCmd := &Command{Use: "child", Run: emptyRun}1610 rootCmd.AddCommand(childCmd)16111612 rootCmd.SetGlobalNormalizationFunc(normFunc)1613 if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {1614 t.Error("rootCmd seems to have a wrong normalization function")1615 }16161617 if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(childCmd.GlobalNormalizationFunc()).Pointer() {1618 t.Error("childCmd should have had the normalization function of rootCmd")1619 }1620}16211622// Related to https://github.com/spf13/cobra/issues/521.1623func TestNormPassedOnLocal(t *testing.T) {1624 toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1625 return pflag.NormalizedName(strings.ToUpper(name))1626 }16271628 c := &Command{}1629 c.Flags().Bool("flagname", true, "this is a dummy flag")1630 c.SetGlobalNormalizationFunc(toUpper)1631 if c.LocalFlags().Lookup("flagname") != c.LocalFlags().Lookup("FLAGNAME") {1632 t.Error("Normalization function should be passed on to Local flag set")1633 }1634}16351636// Related to https://github.com/spf13/cobra/issues/521.1637func TestNormPassedOnInherited(t *testing.T) {1638 toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1639 return pflag.NormalizedName(strings.ToUpper(name))1640 }16411642 c := &Command{}1643 c.SetGlobalNormalizationFunc(toUpper)16441645 child1 := &Command{}1646 c.AddCommand(child1)16471648 c.PersistentFlags().Bool("flagname", true, "")16491650 child2 := &Command{}1651 c.AddCommand(child2)16521653 inherited := child1.InheritedFlags()1654 if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") {1655 t.Error("Normalization function should be passed on to inherited flag set in command added before flag")1656 }16571658 inherited = child2.InheritedFlags()1659 if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") {1660 t.Error("Normalization function should be passed on to inherited flag set in command added after flag")1661 }1662}16631664// Related to https://github.com/spf13/cobra/issues/521.1665func TestConsistentNormalizedName(t *testing.T) {1666 toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1667 return pflag.NormalizedName(strings.ToUpper(name))1668 }1669 n := func(f *pflag.FlagSet, name string) pflag.NormalizedName {1670 return pflag.NormalizedName(name)1671 }16721673 c := &Command{}1674 c.Flags().Bool("flagname", true, "")1675 c.SetGlobalNormalizationFunc(toUpper)1676 c.SetGlobalNormalizationFunc(n)16771678 if c.LocalFlags().Lookup("flagname") == c.LocalFlags().Lookup("FLAGNAME") {1679 t.Error("Normalizing flag names should not result in duplicate flags")1680 }1681}16821683func TestFlagOnPflagCommandLine(t *testing.T) {1684 flagName := "flagOnCommandLine"1685 pflag.String(flagName, "", "about my flag")16861687 c := &Command{Use: "c", Run: emptyRun}1688 c.AddCommand(&Command{Use: "child", Run: emptyRun})16891690 output, _ := executeCommand(c, "--help")1691 checkStringContains(t, output, flagName)16921693 resetCommandLineFlagSet()1694}16951696// TestHiddenCommandExecutes checks,1697// if hidden commands run as intended.1698func TestHiddenCommandExecutes(t *testing.T) {1699 executed := false1700 c := &Command{1701 Use: "c",1702 Hidden: true,1703 Run: func(*Command, []string) { executed = true },1704 }17051706 output, err := executeCommand(c)1707 if output != "" {1708 t.Errorf("Unexpected output: %v", output)1709 }1710 if err != nil {1711 t.Errorf("Unexpected error: %v", err)1712 }17131714 if !executed {1715 t.Error("Hidden command should have been executed")1716 }1717}17181719// test to ensure hidden commands do not show up in usage/help text1720func TestHiddenCommandIsHidden(t *testing.T) {1721 c := &Command{Use: "c", Hidden: true, Run: emptyRun}1722 if c.IsAvailableCommand() {1723 t.Errorf("Hidden command should be unavailable")1724 }1725}17261727func TestCommandsAreSorted(t *testing.T) {1728 EnableCommandSorting = true17291730 originalNames := []string{"middle", "zlast", "afirst"}1731 expectedNames := []string{"afirst", "middle", "zlast"}17321733 var rootCmd = &Command{Use: "root"}17341735 for _, name := range originalNames {1736 rootCmd.AddCommand(&Command{Use: name})1737 }17381739 for i, c := range rootCmd.Commands() {1740 got := c.Name()1741 if expectedNames[i] != got {1742 t.Errorf("Expected: %s, got: %s", expectedNames[i], got)1743 }1744 }1745

Support for case-insensitive command names (#1802)Yuval Goldbergbefore adoptiond689184

line 1746why, one step back
1746 EnableCommandSorting = defaultCommandSorting

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 1747–1766why, one step back
1747}
17481749func TestEnableCommandSortingIsDisabled(t *testing.T) {1750 EnableCommandSorting = false17511752 originalNames := []string{"middle", "zlast", "afirst"}17531754 var rootCmd = &Command{Use: "root"}17551756 for _, name := range originalNames {1757 rootCmd.AddCommand(&Command{Use: name})1758 }17591760 for i, c := range rootCmd.Commands() {1761 got := c.Name()1762 if originalNames[i] != got {1763 t.Errorf("expected: %s, got: %s", originalNames[i], got)1764 }1765 }1766

Support for case-insensitive command names (#1802)Yuval Goldbergbefore adoptiond689184

line 1767why, one step back
1767 EnableCommandSorting = defaultCommandSorting

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 1768–1814why, one step back
1768}
17691770func TestSetOutput(t *testing.T) {1771 c := &Command{}1772 c.SetOutput(nil)1773 if out := c.OutOrStdout(); out != os.Stdout {1774 t.Errorf("Expected setting output to nil to revert back to stdout")1775 }1776}17771778func TestSetOut(t *testing.T) {1779 c := &Command{}1780 c.SetOut(nil)1781 if out := c.OutOrStdout(); out != os.Stdout {1782 t.Errorf("Expected setting output to nil to revert back to stdout")1783 }1784}17851786func TestSetErr(t *testing.T) {1787 c := &Command{}1788 c.SetErr(nil)1789 if out := c.ErrOrStderr(); out != os.Stderr {1790 t.Errorf("Expected setting error to nil to revert back to stderr")1791 }1792}17931794func TestSetIn(t *testing.T) {1795 c := &Command{}1796 c.SetIn(nil)1797 if out := c.InOrStdin(); out != os.Stdin {1798 t.Errorf("Expected setting input to nil to revert back to stdin")1799 }1800}18011802func TestUsageStringRedirected(t *testing.T) {1803 c := &Command{}18041805 c.usageFunc = func(cmd *Command) error {1806 cmd.Print("[stdout1]")1807 cmd.PrintErr("[stderr2]")1808 cmd.Print("[stdout3]")1809 return nil1810 }18111812 expected := "[stdout1][stderr2][stdout3]"1813 if got := c.UsageString(); got != expected {1814 t.Errorf("Expected usage string to consider both stdout and stderr")

Fix stderr printing functions (#894)Alessio Tregliabefore adoption40d34bc

lines 1815–1855why, one step back
1815 }
1816}18171818func TestCommandPrintRedirection(t *testing.T) {1819 errBuff, outBuff := bytes.NewBuffer(nil), bytes.NewBuffer(nil)1820 root := &Command{1821 Run: func(cmd *Command, args []string) {18221823 cmd.PrintErr("PrintErr")1824 cmd.PrintErrln("PrintErr", "line")1825 cmd.PrintErrf("PrintEr%s", "r")18261827 cmd.Print("Print")1828 cmd.Println("Print", "line")1829 cmd.Printf("Prin%s", "t")1830 },1831 }18321833 root.SetErr(errBuff)1834 root.SetOut(outBuff)18351836 if err := root.Execute(); err != nil {1837 t.Error(err)1838 }18391840 gotErrBytes, err := ioutil.ReadAll(errBuff)1841 if err != nil {1842 t.Error(err)1843 }18441845 gotOutBytes, err := ioutil.ReadAll(outBuff)1846 if err != nil {1847 t.Error(err)1848 }18491850 if wantErr := []byte("PrintErrPrintErr line\nPrintErr"); !bytes.Equal(gotErrBytes, wantErr) {1851 t.Errorf("got: '%s' want: '%s'", gotErrBytes, wantErr)1852 }18531854 if wantOut := []byte("PrintPrint line\nPrint"); !bytes.Equal(gotOutBytes, wantOut) {1855 t.Errorf("got: '%s' want: '%s'", gotOutBytes, wantOut)

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 1856–1875why, one step back
1856 }
1857}18581859func TestFlagErrorFunc(t *testing.T) {1860 c := &Command{Use: "c", Run: emptyRun}18611862 expectedFmt := "This is expected: %v"1863 c.SetFlagErrorFunc(func(_ *Command, err error) error {1864 return fmt.Errorf(expectedFmt, err)1865 })18661867 _, err := executeCommand(c, "--unknown-flag")18681869 got := err.Error()1870 expected := fmt.Sprintf(expectedFmt, "unknown flag: --unknown-flag")1871 if got != expected {1872 t.Errorf("Expected %v, got %v", expected, got)1873 }1874}1875

use errors.Is() to check for errors (#1730)Paul Holzingerbefore adoptionb9ca594

lines 1876–1907why, one step back
1876func TestFlagErrorFuncHelp(t *testing.T) {
1877 c := &Command{Use: "c", Run: emptyRun}1878 c.PersistentFlags().Bool("help", false, "help for c")1879 c.SetFlagErrorFunc(func(_ *Command, err error) error {1880 return fmt.Errorf("wrap error: %w", err)1881 })18821883 out, err := executeCommand(c, "--help")1884 if err != nil {1885 t.Errorf("--help should not fail: %v", err)1886 }18871888 expected := `Usage:1889 c [flags]18901891Flags:1892 --help help for c1893`1894 if out != expected {1895 t.Errorf("Expected: %v, got: %v", expected, out)1896 }18971898 out, err = executeCommand(c, "-h")1899 if err != nil {1900 t.Errorf("-h should not fail: %v", err)1901 }19021903 if out != expected {1904 t.Errorf("Expected: %v, got: %v", expected, out)1905 }1906}1907

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 1908–1953why, one step back
1908// TestSortedFlags checks,
1909// if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false.1910// Related to https://github.com/spf13/cobra/issues/404.1911func TestSortedFlags(t *testing.T) {1912 c := &Command{}1913 c.Flags().SortFlags = false1914 names := []string{"C", "B", "A", "D"}1915 for _, name := range names {1916 c.Flags().Bool(name, false, "")1917 }19181919 i := 01920 c.LocalFlags().VisitAll(func(f *pflag.Flag) {1921 if i == len(names) {1922 return1923 }1924 if stringInSlice(f.Name, names) {1925 if names[i] != f.Name {1926 t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name)1927 }1928 i++1929 }1930 })1931}19321933// TestMergeCommandLineToFlags checks,1934// if pflag.CommandLine is correctly merged to c.Flags() after first call1935// of c.mergePersistentFlags.1936// Related to https://github.com/spf13/cobra/issues/443.1937func TestMergeCommandLineToFlags(t *testing.T) {1938 pflag.Bool("boolflag", false, "")1939 c := &Command{Use: "c", Run: emptyRun}1940 c.mergePersistentFlags()1941 if c.Flags().Lookup("boolflag") == nil {1942 t.Fatal("Expecting to have flag from CommandLine in c.Flags()")1943 }19441945 resetCommandLineFlagSet()1946}19471948// TestUseDeprecatedFlags checks,1949// if cobra.Execute() prints a message, if a deprecated flag is used.1950// Related to https://github.com/spf13/cobra/issues/463.1951func TestUseDeprecatedFlags(t *testing.T) {1952 c := &Command{Use: "c", Run: emptyRun}1953 c.Flags().BoolP("deprecated", "d", false, "deprecated flag")

Use golangci-lint (#1044)Unai Martinez-Corralbefore adoption652c755

line 1954why, one step back
1954 assertNoErr(t, c.Flags().MarkDeprecated("deprecated", "This flag is deprecated"))

Move projects using Cobra (#1090)Warren Fernandesbefore adoption090d94f

lines 1955–2101why, one step back
1955
1956 output, err := executeCommand(c, "c", "-d")1957 if err != nil {1958 t.Error("Unexpected error:", err)1959 }1960 checkStringContains(t, output, "This flag is deprecated")1961}19621963func TestTraverseWithParentFlags(t *testing.T) {1964 rootCmd := &Command{Use: "root", TraverseChildren: true}1965 rootCmd.Flags().String("str", "", "")1966 rootCmd.Flags().BoolP("bool", "b", false, "")19671968 childCmd := &Command{Use: "child"}1969 childCmd.Flags().Int("int", -1, "")19701971 rootCmd.AddCommand(childCmd)19721973 c, args, err := rootCmd.Traverse([]string{"-b", "--str", "ok", "child", "--int"})1974 if err != nil {1975 t.Errorf("Unexpected error: %v", err)1976 }1977 if len(args) != 1 && args[0] != "--add" {1978 t.Errorf("Wrong args: %v", args)1979 }1980 if c.Name() != childCmd.Name() {1981 t.Errorf("Expected command: %q, got: %q", childCmd.Name(), c.Name())1982 }1983}19841985func TestTraverseNoParentFlags(t *testing.T) {1986 rootCmd := &Command{Use: "root", TraverseChildren: true}1987 rootCmd.Flags().String("foo", "", "foo things")19881989 childCmd := &Command{Use: "child"}1990 childCmd.Flags().String("str", "", "")1991 rootCmd.AddCommand(childCmd)19921993 c, args, err := rootCmd.Traverse([]string{"child"})1994 if err != nil {1995 t.Errorf("Unexpected error: %v", err)1996 }1997 if len(args) != 0 {1998 t.Errorf("Wrong args %v", args)1999 }2000 if c.Name() != childCmd.Name() {

The first 2,000 of 2,345 lines.