From acc7654e4187dd33e415e7d5cab4cbd708c1c4e2 Mon Sep 17 00:00:00 2001 From: Naveen Gogineni Date: Tue, 26 Dec 2023 17:17:41 -0500 Subject: [PATCH] Fix:(issue_1695) Change tests to use assert and require --- command_test.go | 644 +++++++++++---------------------- completion_test.go | 18 +- errors_test.go | 36 +- flag_bool_with_inverse_test.go | 28 +- flag_mutex_test.go | 14 +- flag_test.go | 584 +++++++++--------------------- help_test.go | 232 +++--------- helpers_test.go | 10 - sort_test.go | 10 +- suggestions_test.go | 16 +- 10 files changed, 487 insertions(+), 1105 deletions(-) diff --git a/command_test.go b/command_test.go index 9c62daad97..a23672ee7b 100644 --- a/command_test.go +++ b/command_test.go @@ -9,13 +9,13 @@ import ( "io" "net/mail" "os" - "reflect" "sort" "strconv" "strings" "testing" "time" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -277,10 +277,9 @@ func TestCommand_Run_DoesNotOverwriteErrorFromBefore(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"bar"}) - r := require.New(t) - r.ErrorContains(err, "before error") - r.ErrorContains(err, "after error") + require.ErrorContains(t, err, "before error") + require.ErrorContains(t, err, "after error") } func TestCommand_Run_BeforeSavesMetadata(t *testing.T) { @@ -311,11 +310,9 @@ func TestCommand_Run_BeforeSavesMetadata(t *testing.T) { }, } - r := require.New(t) - - r.NoError(cmd.Run(buildTestContext(t), []string{"foo", "bar"})) - r.Equal("hello world", receivedMsgFromAction) - r.Equal("hello world", receivedMsgFromAfter) + require.NoError(t, cmd.Run(buildTestContext(t), []string{"foo", "bar"})) + require.Equal(t, "hello world", receivedMsgFromAction) + require.Equal(t, "hello world", receivedMsgFromAfter) } func TestCommand_OnUsageError_hasCommandContext(t *testing.T) { @@ -330,13 +327,7 @@ func TestCommand_OnUsageError_hasCommandContext(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"bar", "--flag=wrong"}) - if err == nil { - t.Fatalf("expected to receive error from Run, got none") - } - - if !strings.HasPrefix(err.Error(), "intercepted in bar") { - t.Errorf("Expect an intercepted error, but got \"%v\"", err) - } + assert.ErrorContains(t, err, "intercepted in bar") } func TestCommand_OnUsageError_WithWrongFlagValue(t *testing.T) { @@ -346,21 +337,13 @@ func TestCommand_OnUsageError_WithWrongFlagValue(t *testing.T) { &IntFlag{Name: "flag"}, }, OnUsageError: func(_ context.Context, _ *Command, err error, _ bool) error { - if !strings.HasPrefix(err.Error(), "invalid value \"wrong\"") { - t.Errorf("Expect an invalid value error, but got \"%v\"", err) - } + assert.ErrorContains(t, err, "invalid value \"wrong\"") return errors.New("intercepted: " + err.Error()) }, } err := cmd.Run(buildTestContext(t), []string{"bar", "--flag=wrong"}) - if err == nil { - t.Fatalf("expected to receive error from Run, got none") - } - - if !strings.HasPrefix(err.Error(), "intercepted: invalid value") { - t.Errorf("Expect an intercepted error, but got \"%v\"", err) - } + assert.ErrorContains(t, err, "intercepted: invalid value") } func TestCommand_OnUsageError_WithSubcommand(t *testing.T) { @@ -375,9 +358,7 @@ func TestCommand_OnUsageError_WithSubcommand(t *testing.T) { &IntFlag{Name: "flag"}, }, OnUsageError: func(_ context.Context, _ *Command, err error, _ bool) error { - if !strings.HasPrefix(err.Error(), "invalid value \"wrong\"") { - t.Errorf("Expect an invalid value error, but got \"%v\"", err) - } + assert.ErrorContains(t, err, "invalid value \"wrong\"") return errors.New("intercepted: " + err.Error()) }, } @@ -433,8 +414,8 @@ func TestCommandSkipFlagParsing(t *testing.T) { } err := cmd.Run(buildTestContext(t), c.testArgs.Slice()) - expect(t, err, c.expectedErr) - expect(t, args, c.expectedArgs) + assert.Equal(t, c.expectedErr, err) + assert.Equal(t, c.expectedArgs, args) }) } } @@ -499,7 +480,7 @@ func TestCommand_CanAddVFlagOnSubCommands(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo", "bar"}) - expect(t, err, nil) + assert.NoError(t, err) } func TestCommand_VisibleSubcCommands(t *testing.T) { @@ -525,7 +506,7 @@ func TestCommand_VisibleSubcCommands(t *testing.T) { }, } - expect(t, cmd.VisibleCommands(), []*Command{subc1, subc3}) + assert.Equal(t, cmd.VisibleCommands(), []*Command{subc1, subc3}) } func TestCommand_VisibleFlagCategories(t *testing.T) { @@ -545,20 +526,13 @@ func TestCommand_VisibleFlagCategories(t *testing.T) { } vfc := cmd.VisibleFlagCategories() - if len(vfc) != 1 { - t.Fatalf("unexpected visible flag categories %+v", vfc) - } - if vfc[0].Name() != "cat1" { - t.Errorf("expected category name cat1 got %s", vfc[0].Name()) - } - if len(vfc[0].Flags()) != 1 { - t.Fatalf("expected flag category to have just one flag got %+v", vfc[0].Flags()) - } + require.NotEmpty(t, vfc) + assert.Equal(t, vfc[0].Name(), "cat1", "expected category name cat1") + + require.Len(t, vfc[0].Flags(), 1, "expected flag category to have just one flag") fl := vfc[0].Flags()[0] - if !reflect.DeepEqual(fl.Names(), []string{"intd", "altd1", "altd2"}) { - t.Errorf("unexpected flag %+v", fl.Names()) - } + assert.Equal(t, fl.Names(), []string{"intd", "altd1", "altd2"}) } func TestCommand_RunSubcommandWithDefault(t *testing.T) { @@ -585,10 +559,10 @@ func TestCommand_RunSubcommandWithDefault(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"app", "bar"}) - expect(t, err, nil) + assert.NoError(t, err) err = cmd.Run(buildTestContext(t), []string{"app"}) - expect(t, err, errors.New("should not run this subcommand")) + assert.EqualError(t, err, "should not run this subcommand") } func TestCommand_Run(t *testing.T) { @@ -602,10 +576,10 @@ func TestCommand_Run(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"command", "foo"}) - expect(t, err, nil) + assert.NoError(t, err) err = cmd.Run(buildTestContext(t), []string{"command", "bar"}) - expect(t, err, nil) - expect(t, s, "foobar") + assert.NoError(t, err) + assert.Equal(t, s, "foobar") } var commandTests = []struct { @@ -629,7 +603,11 @@ func TestCommand_Command(t *testing.T) { } for _, test := range commandTests { - expect(t, cmd.Command(test.name) != nil, test.expected) + if test.expected { + assert.NotEmpty(t, cmd.Command(test.name)) + } else { + assert.Empty(t, cmd.Command(test.name)) + } } } @@ -663,7 +641,11 @@ func TestCommand_RunDefaultCommand(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"c", test.cmdName}) - expect(t, err == nil, test.expected) + if test.expected { + assert.NoError(t, err) + } else { + assert.Error(t, err) + } }) } } @@ -717,7 +699,11 @@ func TestCommand_RunDefaultCommandWithSubCommand(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"c", test.cmdName, test.subCmd}) - expect(t, err == nil, test.expected) + if test.expected { + assert.NoError(t, err) + } else { + assert.Error(t, err) + } }) } } @@ -797,7 +783,11 @@ func TestCommand_RunDefaultCommandWithFlags(t *testing.T) { appArgs = append(appArgs, test.cmdName) err := cmd.Run(buildTestContext(t), appArgs) - expect(t, err == nil, test.expected) + if test.expected { + assert.NoError(t, err) + } else { + assert.Error(t, err) + } }) } } @@ -829,13 +819,9 @@ func TestCommand_FlagsFromExtPackage(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo", "-c", "cly", "--epflag", "10"}) - if err != nil { - t.Error(err) - } + assert.NoError(t, err) - if someint != 10 { - t.Errorf("Expected 10 got %d for someint", someint) - } + assert.Equal(t, someint, int(10)) cmd = &Command{ Flags: []Flag{ @@ -855,21 +841,19 @@ func TestCommand_FlagsFromExtPackage(t *testing.T) { // this should return an error since epflag shouldnt be registered err = cmd.Run(buildTestContext(t), []string{"foo", "-c", "cly", "--epflag", "10"}) - if err == nil { - t.Error("Expected error") - } + assert.Error(t, err) } func TestCommand_Setup_defaultsReader(t *testing.T) { cmd := &Command{} cmd.setupDefaults([]string{"cli.test"}) - expect(t, cmd.Reader, os.Stdin) + assert.Equal(t, cmd.Reader, os.Stdin) } func TestCommand_Setup_defaultsWriter(t *testing.T) { cmd := &Command{} cmd.setupDefaults([]string{"cli.test"}) - expect(t, cmd.Writer, os.Stdout) + assert.Equal(t, cmd.Writer, os.Stdout) } func TestCommand_CommandWithFlagBeforeTerminator(t *testing.T) { @@ -892,14 +876,12 @@ func TestCommand_CommandWithFlagBeforeTerminator(t *testing.T) { }, } - r := require.New(t) - - r.NoError(cmd.Run(buildTestContext(t), []string{"", "cmd", "--option", "my-option", "my-arg", "--", "--notARealFlag"})) + require.NoError(t, cmd.Run(buildTestContext(t), []string{"", "cmd", "--option", "my-option", "my-arg", "--", "--notARealFlag"})) - r.Equal("my-option", parsedOption) - r.Equal("my-arg", args.Get(0)) - r.Equal("--", args.Get(1)) - r.Equal("--notARealFlag", args.Get(2)) + require.Equal(t, "my-option", parsedOption) + require.Equal(t, "my-arg", args.Get(0)) + require.Equal(t, "--", args.Get(1)) + require.Equal(t, "--notARealFlag", args.Get(2)) } func TestCommand_CommandWithDash(t *testing.T) { @@ -917,12 +899,10 @@ func TestCommand_CommandWithDash(t *testing.T) { }, } - r := require.New(t) - - r.NoError(cmd.Run(buildTestContext(t), []string{"", "cmd", "my-arg", "-"})) - r.NotNil(args) - r.Equal("my-arg", args.Get(0)) - r.Equal("-", args.Get(1)) + require.NoError(t, cmd.Run(buildTestContext(t), []string{"", "cmd", "my-arg", "-"})) + require.NotNil(t, args) + require.Equal(t, "my-arg", args.Get(0)) + require.Equal(t, "-", args.Get(1)) } func TestCommand_CommandWithNoFlagBeforeTerminator(t *testing.T) { @@ -940,14 +920,12 @@ func TestCommand_CommandWithNoFlagBeforeTerminator(t *testing.T) { }, } - r := require.New(t) - - r.NoError(cmd.Run(buildTestContext(t), []string{"", "cmd", "my-arg", "--", "notAFlagAtAll"})) + require.NoError(t, cmd.Run(buildTestContext(t), []string{"", "cmd", "my-arg", "--", "notAFlagAtAll"})) - r.NotNil(args) - r.Equal("my-arg", args.Get(0)) - r.Equal("--", args.Get(1)) - r.Equal("notAFlagAtAll", args.Get(2)) + require.NotNil(t, args) + require.Equal(t, "my-arg", args.Get(0)) + require.Equal(t, "--", args.Get(1)) + require.Equal(t, "notAFlagAtAll", args.Get(2)) } func TestCommand_SkipFlagParsing(t *testing.T) { @@ -963,9 +941,9 @@ func TestCommand_SkipFlagParsing(t *testing.T) { _ = cmd.Run(buildTestContext(t), []string{"", "--", "my-arg", "notAFlagAtAll"}) - expect(t, args.Get(0), "--") - expect(t, args.Get(1), "my-arg") - expect(t, args.Get(2), "notAFlagAtAll") + assert.Equal(t, args.Get(0), "--") + assert.Equal(t, args.Get(1), "my-arg") + assert.Equal(t, args.Get(2), "notAFlagAtAll") } func TestCommand_VisibleCommands(t *testing.T) { @@ -989,13 +967,13 @@ func TestCommand_VisibleCommands(t *testing.T) { cmd.Commands[2], // help } actual := cmd.VisibleCommands() - expect(t, len(expected), len(actual)) + assert.Len(t, actual, len(expected)) for i, actualCommand := range actual { expectedCommand := expected[i] if expectedCommand.Action != nil { // comparing func addresses is OK! - expect(t, fmt.Sprintf("%p", expectedCommand.Action), fmt.Sprintf("%p", actualCommand.Action)) + assert.Equal(t, fmt.Sprintf("%p", expectedCommand.Action), fmt.Sprintf("%p", actualCommand.Action)) } func() { @@ -1010,9 +988,7 @@ func TestCommand_VisibleCommands(t *testing.T) { expectedCommand.Action = nil actualCommand.Action = nil - if !reflect.DeepEqual(expectedCommand, actualCommand) { - t.Errorf("expected\n%#v\n!=\n%#v", expectedCommand, actualCommand) - } + assert.Equal(t, expectedCommand, actualCommand) }() } } @@ -1037,9 +1013,9 @@ func TestCommand_UseShortOptionHandling(t *testing.T) { } _ = cmd.Run(buildTestContext(t), []string{"", "-on", expected}) - expect(t, one, true) - expect(t, two, false) - expect(t, name, expected) + assert.True(t, one) + assert.False(t, two) + assert.Equal(t, name, expected) } func TestCommand_UseShortOptionHandling_missing_value(t *testing.T) { @@ -1050,7 +1026,7 @@ func TestCommand_UseShortOptionHandling_missing_value(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"", "-n"}) - expect(t, err, errors.New("flag needs an argument: -n")) + assert.EqualError(t, err, "flag needs an argument: -n") } func TestCommand_UseShortOptionHandlingCommand(t *testing.T) { @@ -1077,11 +1053,10 @@ func TestCommand_UseShortOptionHandlingCommand(t *testing.T) { Writer: io.Discard, } - r := require.New(t) - r.Nil(cmd.Run(buildTestContext(t), []string{"cmd", "-on", expected})) - r.True(one) - r.False(two) - r.Equal(expected, name) + require.NoError(t, cmd.Run(buildTestContext(t), []string{"cmd", "-on", expected})) + require.True(t, one) + require.False(t, two) + require.Equal(t, expected, name) } func TestCommand_UseShortOptionHandlingCommand_missing_value(t *testing.T) { @@ -1095,7 +1070,7 @@ func TestCommand_UseShortOptionHandlingCommand_missing_value(t *testing.T) { } cmd.Commands = []*Command{command} - require.ErrorContains( + require.EqualError( t, cmd.Run(buildTestContext(t), []string{"", "cmd", "-n"}), "flag needs an argument: -n", @@ -1130,14 +1105,12 @@ func TestCommand_UseShortOptionHandlingSubCommand(t *testing.T) { }, } - r := require.New(t) - expected := "expectedName" - r.NoError(cmd.Run(buildTestContext(t), []string{"", "cmd", "sub", "-on", expected})) - r.True(one) - r.False(two) - r.Equal(expected, name) + require.NoError(t, cmd.Run(buildTestContext(t), []string{"", "cmd", "sub", "-on", expected})) + require.True(t, one) + require.False(t, two) + require.Equal(t, expected, name) } func TestCommand_UseShortOptionHandlingSubCommand_missing_value(t *testing.T) { @@ -1156,7 +1129,7 @@ func TestCommand_UseShortOptionHandlingSubCommand_missing_value(t *testing.T) { cmd.Commands = []*Command{command} err := cmd.Run(buildTestContext(t), []string{"", "cmd", "sub", "-n"}) - expect(t, err, errors.New("flag needs an argument: -n")) + assert.EqualError(t, err, "flag needs an argument: -n") } func TestCommand_UseShortOptionAfterSliceFlag(t *testing.T) { @@ -1183,11 +1156,11 @@ func TestCommand_UseShortOptionAfterSliceFlag(t *testing.T) { } _ = cmd.Run(buildTestContext(t), []string{"", "-e", "foo", "-on", expected}) - expect(t, sliceVal, []string{"foo"}) - expect(t, sliceValDest, []string{"foo"}) - expect(t, one, true) - expect(t, two, false) - expect(t, name, expected) + assert.Equal(t, sliceVal, []string{"foo"}) + assert.Equal(t, sliceValDest, []string{"foo"}) + assert.True(t, one) + assert.False(t, two) + assert.Equal(t, expected, name) } func TestCommand_Float64Flag(t *testing.T) { @@ -1204,7 +1177,7 @@ func TestCommand_Float64Flag(t *testing.T) { } _ = cmd.Run(buildTestContext(t), []string{"", "--height", "1.93"}) - expect(t, meters, 1.93) + assert.Equal(t, 1.93, meters) } func TestCommand_ParseSliceFlags(t *testing.T) { @@ -1267,18 +1240,14 @@ func TestCommand_DefaultStdin(t *testing.T) { cmd := &Command{} cmd.setupDefaults([]string{"cli.test"}) - if cmd.Reader != os.Stdin { - t.Error("Default input reader not set.") - } + assert.Equal(t, cmd.Reader, os.Stdin, "Default input reader not set.") } func TestCommand_DefaultStdout(t *testing.T) { cmd := &Command{} cmd.setupDefaults([]string{"cli.test"}) - if cmd.Writer != os.Stdout { - t.Error("Default output writer not set.") - } + assert.Equal(t, cmd.Writer, os.Stdout, "Default output writer not set.") } func TestCommand_SetStdin(t *testing.T) { @@ -1294,13 +1263,8 @@ func TestCommand_SetStdin(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"help"}) - if err != nil { - t.Fatalf("Run error: %s", err) - } - - if string(buf) != "Hello World!" { - t.Error("Command did not read input from desired reader.") - } + require.NoError(t, err) + assert.Equal(t, "Hello World!", string(buf), "Command did not read input from desired reader.") } func TestCommand_SetStdin_Subcommand(t *testing.T) { @@ -1326,13 +1290,8 @@ func TestCommand_SetStdin_Subcommand(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"test", "command", "subcommand"}) - if err != nil { - t.Fatalf("Run error: %s", err) - } - - if string(buf) != "Hello World!" { - t.Error("Command did not read input from desired reader.") - } + require.NoError(t, err) + assert.Equal(t, "Hello World!", string(buf), "Command did not read input from desired reader.") } func TestCommand_SetStdout(t *testing.T) { @@ -1344,13 +1303,8 @@ func TestCommand_SetStdout(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"help"}) - if err != nil { - t.Fatalf("Run error: %s", err) - } - - if w.Len() == 0 { - t.Error("Command did not write output to desired writer.") - } + require.NoError(t, err) + assert.NotZero(t, w.Len(), "Command did not write output to desired writer.") } func TestCommand_BeforeFunc(t *testing.T) { @@ -1387,18 +1341,10 @@ func TestCommand_BeforeFunc(t *testing.T) { // run with the Before() func succeeding err = cmd.Run(buildTestContext(t), []string{"command", "--opt", "succeed", "sub"}) + require.NoError(t, err) - if err != nil { - t.Fatalf("Run error: %s", err) - } - - if counts.Before != 1 { - t.Errorf("Before() not executed when expected") - } - - if counts.SubCommand != 2 { - t.Errorf("Subcommand not executed when expected") - } + assert.Equal(t, 1, counts.Before, "Before() not executed when expected") + assert.Equal(t, 2, counts.SubCommand, "Subcommand not executed when expected") // reset counts = &opCounts{} @@ -1407,17 +1353,9 @@ func TestCommand_BeforeFunc(t *testing.T) { err = cmd.Run(buildTestContext(t), []string{"command", "--opt", "fail", "sub"}) // should be the same error produced by the Before func - if err != beforeError { - t.Errorf("Run error expected, but not received") - } - - if counts.Before != 1 { - t.Errorf("Before() not executed when expected") - } - - if counts.SubCommand != 0 { - t.Errorf("Subcommand executed when NOT expected") - } + assert.ErrorIs(t, err, beforeError, "Run error expected, but not received") + assert.Equal(t, 1, counts.Before, "Before() not executed when expected") + assert.Equal(t, 0, counts.SubCommand, "Subcommand executed when NOT expected") // reset counts = &opCounts{} @@ -1435,13 +1373,8 @@ func TestCommand_BeforeFunc(t *testing.T) { t.Errorf("MultiError expected, but not received") } - if counts.Before != 1 { - t.Errorf("Before() not executed when expected") - } - - if counts.SubCommand != 0 { - t.Errorf("Subcommand executed when NOT expected") - } + assert.Equal(t, 1, counts.Before, "Before() not executed when expected") + assert.Zero(t, counts.SubCommand, "Subcommand executed when NOT expected") } func TestCommand_BeforeAfterFuncShellCompletion(t *testing.T) { @@ -1529,18 +1462,9 @@ func TestCommand_AfterFunc(t *testing.T) { // run with the After() func succeeding err = cmd.Run(buildTestContext(t), []string{"command", "--opt", "succeed", "sub"}) - - if err != nil { - t.Fatalf("Run error: %s", err) - } - - if counts.After != 2 { - t.Errorf("After() not executed when expected") - } - - if counts.SubCommand != 1 { - t.Errorf("Subcommand not executed when expected") - } + require.NoError(t, err) + assert.Equal(t, 2, counts.After, "After() not executed when expected") + assert.Equal(t, 1, counts.SubCommand, "Subcommand not executed when expected") // reset counts = &opCounts{} @@ -1549,17 +1473,9 @@ func TestCommand_AfterFunc(t *testing.T) { err = cmd.Run(buildTestContext(t), []string{"command", "--opt", "fail", "sub"}) // should be the same error produced by the Before func - if err != afterError { - t.Errorf("Run error expected, but not received") - } - - if counts.After != 2 { - t.Errorf("After() not executed when expected") - } - - if counts.SubCommand != 1 { - t.Errorf("Subcommand not executed when expected") - } + assert.ErrorIs(t, err, afterError, "Run error expected, but not received") + assert.Equal(t, 2, counts.After, "After() not executed when expected") + assert.Equal(t, 1, counts.SubCommand, "Subcommand not executed when expected") /* reset @@ -1574,17 +1490,10 @@ func TestCommand_AfterFunc(t *testing.T) { err = cmd.Run(buildTestContext(t), []string{"command"}) // should be the same error produced by the Before func - if err != nil { - t.Fatalf("Run error: %s", err) - } + require.NoError(t, err) - if counts.After != 1 { - t.Errorf("After() not executed when expected") - } - - if counts.SubCommand != 0 { - t.Errorf("Subcommand not executed when expected") - } + assert.Equal(t, 1, counts.After, "After() not executed when expected") + assert.Equal(t, 0, counts.SubCommand, "Subcommand not executed when expected") } func TestCommandNoHelpFlag(t *testing.T) { @@ -1599,9 +1508,7 @@ func TestCommandNoHelpFlag(t *testing.T) { err := cmd.Run(buildTestContext(t), []string{"test", "-h"}) - if err != flag.ErrHelp { - t.Errorf("expected error about missing help flag, but got: %s (%T)", err, err) - } + assert.ErrorIs(t, err, flag.ErrHelp, "expected error about missing help flag") } func TestRequiredFlagCommandRunBehavior(t *testing.T) { @@ -1733,14 +1640,13 @@ func TestRequiredFlagCommandRunBehavior(t *testing.T) { err := cmd.Run(buildTestContext(t), test.appRunInput) // assertions - if test.expectedAnError && err == nil { - t.Errorf("expected an error, but there was none") - } - if _, ok := err.(requiredFlagsErr); test.expectedAnError && !ok { - t.Errorf("expected a requiredFlagsErr, but got: %s", err) - } - if !test.expectedAnError && err != nil { - t.Errorf("did not expected an error, but there was one: %s", err) + if test.expectedAnError { + assert.Error(t, err) + if _, ok := err.(requiredFlagsErr); test.expectedAnError && !ok { + t.Errorf("expected a requiredFlagsErr, but got: %s", err) + } + } else { + assert.NoError(t, err) } }) } @@ -1761,9 +1667,7 @@ func TestCommandHelpPrinter(t *testing.T) { _ = cmd.Run(buildTestContext(t), []string{"-h"}) - if wasCalled == false { - t.Errorf("Help printer expected to be called, but was not") - } + assert.True(t, wasCalled, "Help printer expected to be called, but was not") } func TestCommand_VersionPrinter(t *testing.T) { @@ -1780,9 +1684,7 @@ func TestCommand_VersionPrinter(t *testing.T) { cmd := &Command{} ShowVersion(cmd) - if wasCalled == false { - t.Errorf("Version printer expected to be called, but was not") - } + assert.True(t, wasCalled, "Version printer expected to be called, but was not") } func TestCommand_CommandNotFound(t *testing.T) { @@ -1806,9 +1708,9 @@ func TestCommand_CommandNotFound(t *testing.T) { _ = cmd.Run(buildTestContext(t), []string{"command", "foo"}) - expect(t, counts.CommandNotFound, 1) - expect(t, counts.SubCommand, 0) - expect(t, counts.Total, 1) + assert.Equal(t, 1, counts.CommandNotFound, 1) + assert.Equal(t, 0, counts.SubCommand) + assert.Equal(t, 1, counts.Total) } func TestCommand_OrderOfOperations(t *testing.T) { @@ -1947,9 +1849,7 @@ func TestCommand_OrderOfOperations(t *testing.T) { r := require.New(t) err := cmd.Run(buildTestContext(t), []string{"command", "bar"}) - if err == nil { - t.Fatalf("expected a non-nil error") - } + r.Error(err) r.Equal(0, counts.OnUsageError) r.Equal(1, counts.Before) r.Equal(2, counts.SubCommand) @@ -1999,24 +1899,18 @@ func TestCommand_Run_CommandWithSubcommandHasHelpTopic(t *testing.T) { } err := cmd.Run(buildTestContext(t), flagSet) - if err != nil { - t.Error(err) - } + assert.NoError(t, err) output := buf.String() - if strings.Contains(output, "No help topic for") { - t.Errorf("expect a help topic, got none: \n%q", output) - } + assert.NotContains(t, output, "No help topic for", "expect a help topic, got none") for _, shouldContain := range []string{ cmd.Name, cmd.Description, subCmdBar.Name, subCmdBar.Usage, subCmdBaz.Name, subCmdBaz.Usage, } { - if !strings.Contains(output, shouldContain) { - t.Errorf("want help to contain %q, did not: \n%q", shouldContain, output) - } + assert.Contains(t, output, shouldContain, "want help to contain %q, did not: \n%q", shouldContain, output) } }) } @@ -2038,13 +1932,11 @@ func TestCommand_Run_SubcommandFullPath(t *testing.T) { Writer: out, } - r := require.New(t) - - r.NoError(cmd.Run(buildTestContext(t), []string{"foo", "bar", "--help"})) + require.NoError(t, cmd.Run(buildTestContext(t), []string{"foo", "bar", "--help"})) outString := out.String() - r.Contains(outString, "foo bar - does bar things") - r.Contains(outString, "foo bar [command [command options]] [arguments...]") + require.Contains(t, outString, "foo bar - does bar things") + require.Contains(t, outString, "foo bar [command [command options]] [arguments...]") } func TestCommand_Run_Help(t *testing.T) { @@ -2102,15 +1994,13 @@ func TestCommand_Run_Help(t *testing.T) { } err := cmd.Run(buildTestContext(t), tt.helpArguments) - if err != nil && tt.wantErr != nil && err.Error() != tt.wantErr.Error() { - t.Errorf("want err: %s, did note %s\n", tt.wantErr, err) + if tt.wantErr != nil { + assert.ErrorContains(t, err, tt.wantErr.Error()) } output := buf.String() - if !strings.Contains(output, tt.wantContains) { - t.Errorf("want help to contain %q, did not: \n%q", "boom - make an explosive entrance", output) - } + assert.Contains(t, output, tt.wantContains, "want help to contain %q, did not: \n%q", "boom - make an explosive entrance", output) }) } } @@ -2134,15 +2024,8 @@ func TestCommand_Run_Version(t *testing.T) { } err := cmd.Run(buildTestContext(t), args) - if err != nil { - t.Error(err) - } - - output := buf.String() - - if !strings.Contains(output, "0.1.0") { - t.Errorf("want version to contain %q, did not: \n%q", "0.1.0", output) - } + assert.NoError(t, err) + assert.Contains(t, buf.String(), "0.1.0", "want version to contain 0.1.0") }) } } @@ -2188,15 +2071,11 @@ func TestCommand_Run_Categories(t *testing.T) { }, }) - if !reflect.DeepEqual(cmd.categories, &expect) { - t.Fatalf("expected categories %#v, to equal %#v", cmd.categories, &expect) - } + require.Equal(t, &expect, cmd.categories) output := buf.String() - if !strings.Contains(output, "1:\n command1") { - t.Errorf("want buffer to include category %q, did not: \n%q", "1:\n command1", output) - } + assert.Contains(t, output, "1:\n command1", "want buffer to include category %q, did not: \n%q", "1:\n command1", output) } func TestCommand_VisibleCategories(t *testing.T) { @@ -2236,7 +2115,7 @@ func TestCommand_VisibleCategories(t *testing.T) { } cmd.setupDefaults([]string{"cli.test"}) - expect(t, expected, cmd.VisibleCategories()) + assert.Equal(t, expected, cmd.VisibleCategories()) cmd = &Command{ Name: "visible-categories", @@ -2269,7 +2148,7 @@ func TestCommand_VisibleCategories(t *testing.T) { } cmd.setupDefaults([]string{"cli.test"}) - expect(t, expected, cmd.VisibleCategories()) + assert.Equal(t, expected, cmd.VisibleCategories()) cmd = &Command{ Name: "visible-categories", @@ -2294,7 +2173,7 @@ func TestCommand_VisibleCategories(t *testing.T) { } cmd.setupDefaults([]string{"cli.test"}) - expect(t, []CommandCategory{}, cmd.VisibleCategories()) + assert.Empty(t, cmd.VisibleCategories()) } func TestCommand_Run_SubcommandDoesNotOverwriteErrorFromBefore(t *testing.T) { @@ -2314,16 +2193,8 @@ func TestCommand_Run_SubcommandDoesNotOverwriteErrorFromBefore(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo", "bar"}) - if err == nil { - t.Fatalf("expected to receive error from Run, got none") - } - - if !strings.Contains(err.Error(), "before error") { - t.Errorf("expected text of error from Before method, but got none in \"%v\"", err) - } - if !strings.Contains(err.Error(), "after error") { - t.Errorf("expected text of error from After method, but got none in \"%v\"", err) - } + assert.ErrorContains(t, err, "before error") + assert.ErrorContains(t, err, "after error") } func TestCommand_OnUsageError_WithWrongFlagValue_ForSubcommand(t *testing.T) { @@ -2332,12 +2203,8 @@ func TestCommand_OnUsageError_WithWrongFlagValue_ForSubcommand(t *testing.T) { &IntFlag{Name: "flag"}, }, OnUsageError: func(_ context.Context, _ *Command, err error, isSubcommand bool) error { - if isSubcommand { - t.Errorf("Expect subcommand") - } - if !strings.HasPrefix(err.Error(), "invalid value \"wrong\"") { - t.Errorf("Expect an invalid value error, but got \"%v\"", err) - } + assert.False(t, isSubcommand, "Expect subcommand") + assert.ErrorContains(t, err, "invalid value \"wrong\"") return errors.New("intercepted: " + err.Error()) }, Commands: []*Command{ @@ -2348,13 +2215,7 @@ func TestCommand_OnUsageError_WithWrongFlagValue_ForSubcommand(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo", "--flag=wrong", "bar"}) - if err == nil { - t.Fatalf("expected to receive error from Run, got none") - } - - if !strings.HasPrefix(err.Error(), "intercepted: invalid value") { - t.Errorf("Expect an intercepted error, but got \"%v\"", err) - } + assert.ErrorContains(t, err, "intercepted: invalid value", "Expect an intercepted error") } // A custom flag that conforms to the relevant interfaces, but has none of the @@ -2424,9 +2285,7 @@ func TestCustomFlagsUnused(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo"}) - if err != nil { - t.Errorf("Run returned unexpected error: %v", err) - } + assert.NoError(t, err, "Run returned unexpected error") } func TestCustomFlagsUsed(t *testing.T) { @@ -2436,9 +2295,7 @@ func TestCustomFlagsUsed(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo", "--custom=bar"}) - if err != nil { - t.Errorf("Run returned unexpected error: %v", err) - } + assert.NoError(t, err, "Run returned unexpected error") } func TestCustomHelpVersionFlags(t *testing.T) { @@ -2456,26 +2313,20 @@ func TestCustomHelpVersionFlags(t *testing.T) { VersionFlag = &customBoolFlag{"version-custom"} err := cmd.Run(buildTestContext(t), []string{"foo", "--help-custom=bar"}) - if err != nil { - t.Errorf("Run returned unexpected error: %v", err) - } + assert.NoError(t, err, "Run returned unexpected error") } func TestHandleExitCoder_Default(t *testing.T) { app := buildMinimalTestCommand() fs, err := newFlagSet(app.Name, app.Flags) - if err != nil { - t.Errorf("error creating FlagSet: %s", err) - } + assert.NoError(t, err, "error creating FlagSet") app.flagSet = fs _ = app.handleExitCoder(context.Background(), Exit("Default Behavior Error", 42)) output := fakeErrWriter.String() - if !strings.Contains(output, "Default") { - t.Fatalf("Expected Default Behavior from Error Handler but got: %s", output) - } + assert.Contains(t, output, "Default", "Expected Default Behavior from Error Handler") } func TestHandleExitCoder_Custom(t *testing.T) { @@ -2488,9 +2339,7 @@ func TestHandleExitCoder_Custom(t *testing.T) { _ = cmd.handleExitCoder(context.Background(), Exit("Default Behavior Error", 42)) output := fakeErrWriter.String() - if !strings.Contains(output, "Custom") { - t.Fatalf("Expected Custom Behavior from Error Handler but got: %s", output) - } + assert.Contains(t, output, "Custom", "Expected Custom Behavior from Error Handler") } func TestShellCompletionForIncompleteFlags(t *testing.T) { @@ -2535,9 +2384,7 @@ func TestShellCompletionForIncompleteFlags(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"", "--test-completion", "--" + "generate-shell-completion"}) - if err != nil { - t.Errorf("app should not return an error: %s", err) - } + assert.NoError(t, err, "app should not return an error") } func TestWhenExitSubCommandWithCodeThenCommandQuitUnexpectedly(t *testing.T) { @@ -2599,13 +2446,8 @@ func TestSetupInitializesBothWriters(t *testing.T) { cmd.setupDefaults([]string{"cli.test"}) - if cmd.ErrWriter != os.Stderr { - t.Errorf("expected a.ErrWriter to be os.Stderr") - } - - if cmd.Writer != os.Stdout { - t.Errorf("expected a.Writer to be os.Stdout") - } + assert.Equal(t, cmd.ErrWriter, os.Stderr, "expected a.ErrWriter to be os.Stderr") + assert.Equal(t, cmd.Writer, os.Stdout, "expected a.Writer to be os.Stdout") } func TestSetupInitializesOnlyNilWriters(t *testing.T) { @@ -2616,13 +2458,8 @@ func TestSetupInitializesOnlyNilWriters(t *testing.T) { cmd.setupDefaults([]string{"cli.test"}) - if cmd.ErrWriter != wr { - t.Errorf("expected a.ErrWriter to be a *bytes.Buffer instance") - } - - if cmd.Writer != os.Stdout { - t.Errorf("expected a.Writer to be os.Stdout") - } + assert.Equal(t, cmd.ErrWriter, wr, "expected a.ErrWriter to be a *bytes.Buffer instance") + assert.Equal(t, cmd.Writer, os.Stdout, "expected a.Writer to be os.Stdout") } func TestFlagAction(t *testing.T) { @@ -3021,53 +2858,21 @@ func TestPersistentFlag(t *testing.T) { "--persistentCommandFloatSliceFlag", "3.1445", }) - if err != nil { - t.Fatal(err) - } - - if appFlag != "bar" { - t.Errorf("Expected 'bar' got %s", appFlag) - } - - if appRequiredFlag != "hellor" { - t.Errorf("Expected 'hellor' got %s", appRequiredFlag) - } - - if topInt != 12 { - t.Errorf("Expected 12 got %d", topInt) - } + require.NoError(t, err) - if topPersistentInt != 20 { - t.Errorf("Expected 20 got %d", topPersistentInt) - } + assert.Equal(t, "bar", appFlag) + assert.Equal(t, "hellor", appRequiredFlag) + assert.Equal(t, int64(12), topInt) + assert.Equal(t, int64(20), topPersistentInt) // this should be changed from app since // cmd overrides it - if appOverrideInt != 102 { - t.Errorf("Expected 102 got %d", appOverrideInt) - } - - if subCommandInt != 11 { - t.Errorf("Expected 11 got %d", subCommandInt) - } - - if appOverrideCmdInt != 105 { - t.Errorf("Expected 105 got %d", appOverrideCmdInt) - } - - expectedInt := []int64{100, 102, 130} - if !reflect.DeepEqual(persistentCommandSliceInt, expectedInt) { - t.Errorf("Expected %v got %d", expectedInt, persistentCommandSliceInt) - } - - expectedFloat := []float64{102.455, 3.1445} - if !reflect.DeepEqual(appSliceFloat64, expectedFloat) { - t.Errorf("Expected %f got %f", expectedFloat, appSliceFloat64) - } - - if persistentFlagActionCount != 2 { - t.Errorf("Expected persistent flag action to be called 2 times instead called %d", persistentFlagActionCount) - } + assert.Equal(t, int64(102), appOverrideInt) + assert.Equal(t, int64(11), subCommandInt) + assert.Equal(t, int64(105), appOverrideCmdInt) + assert.Equal(t, []int64{100, 102, 130}, persistentCommandSliceInt) + assert.Equal(t, []float64{102.455, 3.1445}, appSliceFloat64) + assert.Equal(t, int64(2), persistentFlagActionCount, "Expected persistent flag action to be called 2 times") } func TestPersistentFlagIsSet(t *testing.T) { @@ -3095,17 +2900,15 @@ func TestPersistentFlagIsSet(t *testing.T) { }, } - r := require.New(t) - err := app.Run(context.Background(), []string{"root", "--result", "before", "sub"}) - r.NoError(err) - r.Equal("before", result) - r.True(resultIsSet) + require.NoError(t, err) + require.Equal(t, "before", result) + require.True(t, resultIsSet) err = app.Run(context.Background(), []string{"root", "sub", "--result", "after"}) - r.NoError(err) - r.Equal("after", result) - r.True(resultIsSet) + require.NoError(t, err) + require.Equal(t, "after", result) + require.True(t, resultIsSet) } func TestRequiredPersistentFlag(t *testing.T) { @@ -3129,13 +2932,11 @@ func TestRequiredPersistentFlag(t *testing.T) { }, } - r := require.New(t) - err := app.Run(context.Background(), []string{"root", "sub"}) - r.Error(err) + require.Error(t, err) err = app.Run(context.Background(), []string{"root", "sub", "--result", "after"}) - r.NoError(err) + require.NoError(t, err) } func TestFlagDuplicates(t *testing.T) { @@ -3189,10 +2990,10 @@ func TestFlagDuplicates(t *testing.T) { } err := cmd.Run(buildTestContext(t), test.args) - if test.errExpected && err == nil { - t.Error("expected error") - } else if !test.errExpected && err != nil { - t.Error(err) + if test.errExpected { + assert.NotNil(t, err) + } else { + assert.Nil(t, err) } }) } @@ -3225,61 +3026,36 @@ func TestShorthandCommand(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo", "cth"}) - if err != nil { - t.Error(err) - } - - if cmd1 != 1 && cmd2 != 0 { - t.Errorf("Expected command1 to be trigerred once but didnt %d %d", cmd1, cmd2) - } + assert.NoError(t, err) + assert.True(t, cmd1 == 1 && cmd2 == 0, "Expected command1 to be trigerred once") cmd1 = 0 cmd2 = 0 err = cmd.Run(buildTestContext(t), []string{"foo", "cthd"}) - if err != nil { - t.Error(err) - } - - if cmd1 != 1 && cmd2 != 0 { - t.Errorf("Expected command1 to be trigerred once but didnt %d %d", cmd1, cmd2) - } + assert.NoError(t, err) + assert.True(t, cmd1 == 1 && cmd2 == 0, "Expected command1 to be trigerred once") cmd1 = 0 cmd2 = 0 err = cmd.Run(buildTestContext(t), []string{"foo", "cthe"}) - if err != nil { - t.Error(err) - } - - if cmd1 != 1 && cmd2 != 0 { - t.Errorf("Expected command1 to be trigerred once but didnt %d %d", cmd1, cmd2) - } + assert.NoError(t, err) + assert.True(t, cmd1 == 1 && cmd2 == 0, "Expected command1 to be trigerred once") cmd1 = 0 cmd2 = 0 err = cmd.Run(buildTestContext(t), []string{"foo", "cthert"}) - if err != nil { - t.Error(err) - } - - if cmd1 != 0 && cmd2 != 1 { - t.Errorf("Expected command1 to be trigerred once but didnt %d %d", cmd1, cmd2) - } + assert.NoError(t, err) + assert.True(t, cmd1 == 0 && cmd2 == 1, "Expected command1 to be trigerred once") cmd1 = 0 cmd2 = 0 err = cmd.Run(buildTestContext(t), []string{"foo", "cthet"}) - if err != nil { - t.Error(err) - } - - if cmd1 != 0 && cmd2 != 1 { - t.Errorf("Expected command1 to be trigerred once but didnt %d %d", cmd1, cmd2) - } + assert.NoError(t, err) + assert.True(t, cmd1 == 0 && cmd2 == 1, "Expected command1 to be trigerred once") } func TestCommand_Int(t *testing.T) { @@ -3291,9 +3067,8 @@ func TestCommand_Int(t *testing.T) { pCmd := &Command{flagSet: parentSet} cmd := &Command{flagSet: set, parent: pCmd} - r := require.New(t) - r.Equal(int64(12), cmd.Int("myflag")) - r.Equal(int64(13), cmd.Int("top-flag")) + require.Equal(t, int64(12), cmd.Int("myflag")) + require.Equal(t, int64(13), cmd.Int("top-flag")) } func TestCommand_Uint(t *testing.T) { @@ -3304,9 +3079,8 @@ func TestCommand_Uint(t *testing.T) { pCmd := &Command{flagSet: parentSet} cmd := &Command{flagSet: set, parent: pCmd} - r := require.New(t) - r.Equal(uint64(13), cmd.Uint("myflagUint")) - r.Equal(uint64(14), cmd.Uint("top-flag")) + require.Equal(t, uint64(13), cmd.Uint("myflagUint")) + require.Equal(t, uint64(14), cmd.Uint("top-flag")) } func TestCommand_Float64(t *testing.T) { @@ -3366,9 +3140,8 @@ func TestCommand_Timestamp(t *testing.T) { }, } - if err := pCmd.Run(context.Background(), []string{"foo", "hello"}); err != nil { - t.Error(err) - } + err := pCmd.Run(context.Background(), []string{"foo", "hello"}) + assert.NoError(t, err) r := require.New(t) r.Equal(t1, cmd.Timestamp("myflag")) @@ -3415,7 +3188,7 @@ func TestCommand_Value(t *testing.T) { r := require.New(t) r.Equal(12, cmd.Value("myflag")) r.Equal(13, cmd.Value("top-flag")) - r.Equal(nil, cmd.Value("unknown-flag")) + r.Nil(cmd.Value("unknown-flag")) } func TestCommand_Value_InvalidFlagAccessHandler(t *testing.T) { @@ -3871,17 +3644,14 @@ func TestCheckRequiredFlags(t *testing.T) { err := cmd.checkRequiredFlags() // assertions - if test.expectedAnError && err == nil { - t.Errorf("expected an error, but there was none") - } - if !test.expectedAnError && err != nil { - t.Errorf("did not expected an error, but there was one: %s", err) + if test.expectedAnError { + assert.NotNil(t, err) + } else { + assert.Nil(t, err) } for _, errString := range test.expectedErrorContents { if err != nil { - if !strings.Contains(err.Error(), errString) { - t.Errorf("expected error %q to contain %q, but it didn't!", err.Error(), errString) - } + assert.ErrorContains(t, err, errString) } } }) @@ -3900,9 +3670,7 @@ func TestCommand_ParentCommand_Set(t *testing.T) { } err := cmd.Set("Name", "aaa") - if err != nil { - t.Errorf("expect nil. set parent context flag return err: %s", err) - } + assert.NoError(t, err) } func TestCommandReadArgsFromStdIn(t *testing.T) { diff --git a/completion_test.go b/completion_test.go index db441e95cf..a9e0c6c0a4 100644 --- a/completion_test.go +++ b/completion_test.go @@ -2,9 +2,9 @@ package cli import ( "bytes" - "strings" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -12,9 +12,7 @@ func TestCompletionDisable(t *testing.T) { cmd := &Command{} err := cmd.Run(buildTestContext(t), []string{"foo", completionCommandName}) - if err == nil { - t.Error("Expected error for no help topic for completion") - } + assert.Error(t, err, "Expected error for no help topic for completion") } func TestCompletionEnable(t *testing.T) { @@ -23,9 +21,7 @@ func TestCompletionEnable(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo", completionCommandName}) - if err == nil || !strings.Contains(err.Error(), "no shell provided") { - t.Errorf("expected no shell provided error instead got [%v]", err) - } + assert.ErrorContains(t, err, "no shell provided") } func TestCompletionEnableDiffCommandName(t *testing.T) { @@ -35,9 +31,7 @@ func TestCompletionEnableDiffCommandName(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo", "junky"}) - if err == nil || !strings.Contains(err.Error(), "no shell provided") { - t.Errorf("expected no shell provided error instead got [%v]", err) - } + assert.ErrorContains(t, err, "no shell provided") } func TestCompletionShell(t *testing.T) { @@ -94,7 +88,5 @@ func TestCompletionInvalidShell(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo", completionCommandName, "junky-sheell"}) - if err == nil { - t.Error("Expected error for invalid shell") - } + assert.ErrorContains(t, err, "unknown shell junky-sheell") } diff --git a/errors_test.go b/errors_test.go index 7594d76348..8d734b621c 100644 --- a/errors_test.go +++ b/errors_test.go @@ -5,6 +5,8 @@ import ( "errors" "fmt" "testing" + + "github.com/stretchr/testify/assert" ) func TestHandleExitCoder_nil(t *testing.T) { @@ -22,8 +24,8 @@ func TestHandleExitCoder_nil(t *testing.T) { HandleExitCoder(nil) - expect(t, exitCode, 0) - expect(t, called, false) + assert.Equal(t, 0, exitCode) + assert.False(t, called) } func TestHandleExitCoder_ExitCoder(t *testing.T) { @@ -41,8 +43,8 @@ func TestHandleExitCoder_ExitCoder(t *testing.T) { HandleExitCoder(Exit("galactic perimeter breach", 9)) - expect(t, exitCode, 9) - expect(t, called, true) + assert.Equal(t, 9, exitCode) + assert.True(t, called) } func TestHandleExitCoder_ErrorExitCoder(t *testing.T) { @@ -60,8 +62,8 @@ func TestHandleExitCoder_ErrorExitCoder(t *testing.T) { HandleExitCoder(Exit(errors.New("galactic perimeter breach"), 9)) - expect(t, exitCode, 9) - expect(t, called, true) + assert.Equal(t, 9, exitCode) + assert.True(t, called) } func TestHandleExitCoder_MultiErrorWithExitCoder(t *testing.T) { @@ -82,8 +84,8 @@ func TestHandleExitCoder_MultiErrorWithExitCoder(t *testing.T) { err := newMultiError(errors.New("wowsa"), errors.New("egad"), exitErr, exitErr2) HandleExitCoder(err) - expect(t, exitCode, 11) - expect(t, called, true) + assert.Equal(t, 11, exitCode) + assert.True(t, called) } func TestHandleExitCoder_MultiErrorWithoutExitCoder(t *testing.T) { @@ -102,8 +104,8 @@ func TestHandleExitCoder_MultiErrorWithoutExitCoder(t *testing.T) { err := newMultiError(errors.New("wowsa"), errors.New("egad")) HandleExitCoder(err) - expect(t, exitCode, 1) - expect(t, called, true) + assert.Equal(t, 1, exitCode) + assert.True(t, called) } // make a stub to not import pkg/errors @@ -137,8 +139,8 @@ func TestHandleExitCoder_ErrorWithFormat(t *testing.T) { err := Exit(NewErrorWithFormat("I am formatted"), 1) HandleExitCoder(err) - expect(t, called, true) - expect(t, ErrWriter.(*bytes.Buffer).String(), "This the format: I am formatted\n") + assert.True(t, called) + assert.Equal(t, ErrWriter.(*bytes.Buffer).String(), "This the format: I am formatted\n") } func TestHandleExitCoder_MultiErrorWithFormat(t *testing.T) { @@ -156,8 +158,8 @@ func TestHandleExitCoder_MultiErrorWithFormat(t *testing.T) { err := newMultiError(NewErrorWithFormat("err1"), NewErrorWithFormat("err2")) HandleExitCoder(err) - expect(t, called, true) - expect(t, ErrWriter.(*bytes.Buffer).String(), "This the format: err1\nThis the format: err2\n") + assert.True(t, called) + assert.Equal(t, ErrWriter.(*bytes.Buffer).String(), "This the format: err1\nThis the format: err2\n") } func TestMultiErrorErrorsCopy(t *testing.T) { @@ -167,17 +169,17 @@ func TestMultiErrorErrorsCopy(t *testing.T) { errors.New("baz"), } me := newMultiError(errList...) - expect(t, errList, me.Errors()) + assert.Equal(t, errList, me.Errors()) } func TestErrRequiredFlags_Error(t *testing.T) { missingFlags := []string{"flag1", "flag2"} err := &errRequiredFlags{missingFlags: missingFlags} expectedMsg := "Required flags \"flag1, flag2\" not set" - expect(t, expectedMsg, err.Error()) + assert.Equal(t, expectedMsg, err.Error()) missingFlags = []string{"flag1"} err = &errRequiredFlags{missingFlags: missingFlags} expectedMsg = "Required flag \"flag1\" not set" - expect(t, expectedMsg, err.Error()) + assert.Equal(t, expectedMsg, err.Error()) } diff --git a/flag_bool_with_inverse_test.go b/flag_bool_with_inverse_test.go index ae18023ca0..9167851e2d 100644 --- a/flag_bool_with_inverse_test.go +++ b/flag_bool_with_inverse_test.go @@ -333,31 +333,13 @@ func TestBoolWithInverseNames(t *testing.T) { } names := flag.Names() - if len(names) != 2 { - t.Errorf("expected 2 names, got %d", len(names)) - return - } - - if names[0] != "env" { - t.Errorf("expected first name to be `env`, got `%s`", names[0]) - return - } - - if names[1] != "no-env" { - t.Errorf("expected first name to be `no-env`, got `%s`", names[1]) - return - } + require.Len(t, names, 2) + require.Equal(t, "env", names[0], "expected first name to be `env`") + require.Equal(t, "no-env", names[1], "expected first name to be `no-env`") flagString := flag.String() - if strings.Contains(flagString, "--env") == false { - t.Errorf("expected `%s` to contain `--env`", flagString) - return - } - - if strings.Contains(flagString, "--no-env") == false { - t.Errorf("expected `%s` to contain `--no-env`", flagString) - return - } + require.Contains(t, flagString, "--env") + require.Contains(t, flagString, "--no-env") } func TestBoolWithInverseDestination(t *testing.T) { diff --git a/flag_mutex_test.go b/flag_mutex_test.go index 61f0a9f0f6..725e277f2a 100644 --- a/flag_mutex_test.go +++ b/flag_mutex_test.go @@ -3,6 +3,8 @@ package cli import ( "strings" "testing" + + "github.com/stretchr/testify/assert" ) func TestFlagMutuallyExclusiveFlags(t *testing.T) { @@ -30,14 +32,10 @@ func TestFlagMutuallyExclusiveFlags(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo"}) - if err != nil { - t.Error(err) - } + assert.NoError(t, err) err = cmd.Run(buildTestContext(t), []string{"foo", "--i", "10"}) - if err != nil { - t.Error(err) - } + assert.NoError(t, err) err = cmd.Run(buildTestContext(t), []string{"foo", "--i", "11", "--ai", "12"}) if err == nil { @@ -60,9 +58,7 @@ func TestFlagMutuallyExclusiveFlags(t *testing.T) { } err = cmd.Run(buildTestContext(t), []string{"foo", "--i", "10"}) - if err != nil { - t.Error(err) - } + assert.NoError(t, err) err = cmd.Run(buildTestContext(t), []string{"foo", "--i", "11", "--ai", "12"}) if err == nil { diff --git a/flag_test.go b/flag_test.go index d973c471de..6f67066411 100644 --- a/flag_test.go +++ b/flag_test.go @@ -11,6 +11,7 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -33,10 +34,7 @@ func TestBoolFlagHelpOutput(t *testing.T) { for _, test := range boolFlagTests { fl := &BoolFlag{Name: test.name} output := fl.String() - - if output != test.expected { - t.Errorf("%q does not match %q", output, test.expected) - } + assert.Equal(t, test.expected, output) } } @@ -47,8 +45,8 @@ func TestBoolFlagApply_SetsAllNames(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--wat", "-W", "--huh"}) - expect(t, err, nil) - expect(t, v, true) + assert.NoError(t, err) + assert.True(t, v) } func TestBoolFlagValueFromCommand(t *testing.T) { @@ -70,12 +68,12 @@ func TestBoolFlagApply_SetsCount(t *testing.T) { fl := BoolFlag{Name: "wat", Aliases: []string{"W", "huh"}, Destination: &v, Config: BoolConfig{Count: &count}} set := flag.NewFlagSet("test", 0) err := fl.Apply(set) - expect(t, err, nil) + assert.NoError(t, err) err = set.Parse([]string{"--wat", "-W", "--huh"}) - expect(t, err, nil) - expect(t, v, true) - expect(t, count, 3) + assert.NoError(t, err) + assert.True(t, v) + assert.Equal(t, 3, count) } func TestBoolFlagCountFromCommand(t *testing.T) { @@ -375,9 +373,9 @@ func TestFlagsFromEnv(t *testing.T) { cmd := &Command{ Flags: []Flag{tc.fl}, Action: func(_ context.Context, cmd *Command) error { - r.Equal(cmd.Value(tc.fl.Names()[0]), tc.output) + r.Equal(tc.output, cmd.Value(tc.fl.Names()[0])) r.True(tc.fl.IsSet()) - r.Equal(cmd.FlagNames(), tc.fl.Names()) + r.Equal(tc.fl.Names(), cmd.FlagNames()) return nil }, @@ -557,9 +555,7 @@ func TestFlagStringifying(t *testing.T) { } { t.Run(tc.name, func(ct *testing.T) { s := stringifyFlag(tc.fl) - if s != tc.expected { - ct.Errorf("stringified flag %q does not match expected %q", s, tc.expected) - } + assert.Equal(t, tc.expected, s, "stringified flag %q does not match expected", s) }) } } @@ -584,26 +580,15 @@ func TestStringFlagHelpOutput(t *testing.T) { fl := &StringFlag{Name: test.name, Aliases: test.aliases, Usage: test.usage, Value: test.value} // create a tmp flagset tfs := flag.NewFlagSet("test", 0) - if err := fl.Apply(tfs); err != nil { - t.Error(err) - return - } - output := fl.String() - - if output != test.expected { - t.Errorf("%q does not match %q", output, test.expected) - } + assert.NoError(t, fl.Apply(tfs)) + assert.Equal(t, test.expected, fl.String()) } } func TestStringFlagDefaultText(t *testing.T) { fl := &StringFlag{Name: "foo", Aliases: nil, Usage: "amount of `foo` requested", Value: "none", DefaultText: "all of it"} expected := "--foo foo\tamount of foo requested (default: all of it)" - output := fl.String() - - if output != expected { - t.Errorf("%q does not match %q", output, expected) - } + assert.Equal(t, expected, fl.String()) } func TestStringFlagWithEnvVarHelpOutput(t *testing.T) { @@ -657,8 +642,8 @@ func TestStringFlagApply_SetsAllNames(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--hay", "u", "-H", "yuu", "--hayyy", "YUUUU"}) - expect(t, err, nil) - expect(t, v, "YUUUU") + assert.NoError(t, err) + assert.Equal(t, "YUUUU", v) } func TestStringFlagValueFromCommand(t *testing.T) { @@ -720,11 +705,7 @@ var stringSliceFlagTests = []struct { func TestStringSliceFlagHelpOutput(t *testing.T) { for _, test := range stringSliceFlagTests { f := &StringSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value} - output := f.String() - - if output != test.expected { - t.Errorf("%q does not match %q", output, test.expected) - } + assert.Equal(t, test.expected, f.String()) } } @@ -750,7 +731,7 @@ func TestStringSliceFlagApply_SetsAllNames(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--goat", "aaa", "-G", "bbb", "--gooots", "eeeee"}) - expect(t, err, nil) + assert.NoError(t, err) } func TestStringSliceFlagApply_UsesEnvValues_noDefault(t *testing.T) { @@ -762,8 +743,8 @@ func TestStringSliceFlagApply_UsesEnvValues_noDefault(t *testing.T) { _ = fl.Apply(set) err := set.Parse(nil) - expect(t, err, nil) - expect(t, set.Lookup("goat").Value.(flag.Getter).Get(), []string{"vincent van goat", "scape goat"}) + assert.NoError(t, err) + assert.Equal(t, []string{"vincent van goat", "scape goat"}, set.Lookup("goat").Value.(flag.Getter).Get()) } func TestStringSliceFlagApply_UsesEnvValues_withDefault(t *testing.T) { @@ -775,8 +756,8 @@ func TestStringSliceFlagApply_UsesEnvValues_withDefault(t *testing.T) { set := flag.NewFlagSet("test", 0) _ = fl.Apply(set) err := set.Parse(nil) - expect(t, err, nil) - expect(t, set.Lookup("goat").Value.(flag.Getter).Get(), []string{"vincent van goat", "scape goat"}) + assert.NoError(t, err) + assert.Equal(t, []string{"vincent van goat", "scape goat"}, set.Lookup("goat").Value.(flag.Getter).Get()) } func TestStringSliceFlagApply_DefaultValueWithDestination(t *testing.T) { @@ -788,8 +769,8 @@ func TestStringSliceFlagApply_DefaultValueWithDestination(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{}) - expect(t, err, nil) - expect(t, defValue, dest) + assert.NoError(t, err) + assert.Equal(t, defValue, dest) } func TestStringSliceFlagValueFromCommand(t *testing.T) { @@ -814,16 +795,8 @@ func TestIntFlagHelpOutput(t *testing.T) { // create a temporary flag set to apply tfs := flag.NewFlagSet("test", 0) - if err := fl.Apply(tfs); err != nil { - t.Error(err) - return - } - - output := fl.String() - - if output != test.expected { - t.Errorf("%s does not match %s", output, test.expected) - } + require.NoError(t, fl.Apply(tfs)) + assert.Equal(t, test.expected, fl.String()) } } @@ -876,16 +849,8 @@ func TestUintFlagHelpOutput(t *testing.T) { // create a temporary flag set to apply tfs := flag.NewFlagSet("test", 0) - if err := fl.Apply(tfs); err != nil { - t.Error(err) - return - } - - output := fl.String() - - if output != test.expected { - t.Errorf("%s does not match %s", output, test.expected) - } + require.NoError(t, fl.Apply(tfs)) + assert.Equal(t, test.expected, fl.String()) } } @@ -927,16 +892,8 @@ func TestUint64FlagHelpOutput(t *testing.T) { // create a temporary flag set to apply tfs := flag.NewFlagSet("test", 0) - if err := fl.Apply(tfs); err != nil { - t.Error(err) - return - } - - output := fl.String() - - if output != test.expected { - t.Errorf("%s does not match %s", output, test.expected) - } + require.NoError(t, fl.Apply(tfs)) + assert.Equal(t, test.expected, fl.String()) } } @@ -978,16 +935,8 @@ func TestDurationFlagHelpOutput(t *testing.T) { // create a temporary flag set to apply tfs := flag.NewFlagSet("test", 0) - if err := fl.Apply(tfs); err != nil { - t.Error(err) - return - } - - output := fl.String() - - if output != test.expected { - t.Errorf("%q does not match %q", output, test.expected) - } + require.NoError(t, fl.Apply(tfs)) + assert.Equal(t, test.expected, fl.String()) } } @@ -1014,8 +963,8 @@ func TestDurationFlagApply_SetsAllNames(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--howmuch", "30s", "-H", "5m", "--whyyy", "30h"}) - expect(t, err, nil) - expect(t, v, time.Hour*30) + assert.NoError(t, err) + assert.Equal(t, time.Hour*30, v) } func TestDurationFlagValueFromCommand(t *testing.T) { @@ -1040,11 +989,7 @@ var intSliceFlagTests = []struct { func TestIntSliceFlagHelpOutput(t *testing.T) { for _, test := range intSliceFlagTests { fl := &IntSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value} - output := fl.String() - - if output != test.expected { - t.Errorf("%q does not match %q", output, test.expected) - } + assert.Equal(t, test.expected, fl.String()) } } @@ -1070,7 +1015,7 @@ func TestIntSliceFlagApply_SetsAllNames(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--bits", "23", "-B", "3", "--bips", "99"}) - expect(t, err, nil) + assert.NoError(t, err) } func TestIntSliceFlagApply_UsesEnvValues_noDefault(t *testing.T) { @@ -1107,8 +1052,8 @@ func TestIntSliceFlagApply_DefaultValueWithDestination(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{}) - expect(t, err, nil) - expect(t, defValue, dest) + assert.NoError(t, err) + assert.Equal(t, defValue, dest) } func TestIntSliceFlagApply_ParentContext(t *testing.T) { @@ -1198,7 +1143,7 @@ func TestUintSliceFlagApply_SetsAllNames(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--bits", "23", "-B", "3", "--bips", "99"}) - expect(t, err, nil) + assert.NoError(t, err) } func TestUintSliceFlagApply_UsesEnvValues_noDefault(t *testing.T) { @@ -1234,8 +1179,8 @@ func TestUintSliceFlagApply_DefaultValueWithDestination(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{}) - expect(t, err, nil) - expect(t, defValue, dest) + assert.NoError(t, err) + assert.Equal(t, defValue, dest) } func TestUintSliceFlagApply_ParentContext(t *testing.T) { @@ -1315,11 +1260,7 @@ var uint64SliceFlagTests = []struct { func TestUint64SliceFlagHelpOutput(t *testing.T) { for _, test := range uint64SliceFlagTests { fl := UintSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value} - output := fl.String() - - if output != test.expected { - t.Errorf("%q does not match %q", output, test.expected) - } + assert.Equal(t, test.expected, fl.String()) } } @@ -1345,7 +1286,7 @@ func TestUint64SliceFlagApply_SetsAllNames(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--bits", "23", "-B", "3", "--bips", "99"}) - expect(t, err, nil) + assert.NoError(t, err) } func TestUint64SliceFlagApply_UsesEnvValues_noDefault(t *testing.T) { @@ -1357,8 +1298,8 @@ func TestUint64SliceFlagApply_UsesEnvValues_noDefault(t *testing.T) { _ = fl.Apply(set) err := set.Parse(nil) - expect(t, err, nil) - expect(t, set.Lookup("goat").Value.(flag.Getter).Get().([]uint64), []uint64{1, 2}) + assert.NoError(t, err) + assert.Equal(t, []uint64{1, 2}, set.Lookup("goat").Value.(flag.Getter).Get().([]uint64)) } func TestUint64SliceFlagApply_UsesEnvValues_withDefault(t *testing.T) { @@ -1370,8 +1311,8 @@ func TestUint64SliceFlagApply_UsesEnvValues_withDefault(t *testing.T) { set := flag.NewFlagSet("test", 0) _ = fl.Apply(set) err := set.Parse(nil) - expect(t, err, nil) - expect(t, set.Lookup("goat").Value.(flag.Getter).Get().([]uint64), []uint64{1, 2}) + assert.NoError(t, err) + assert.Equal(t, []uint64{1, 2}, set.Lookup("goat").Value.(flag.Getter).Get().([]uint64)) } func TestUint64SliceFlagApply_DefaultValueWithDestination(t *testing.T) { @@ -1383,8 +1324,8 @@ func TestUint64SliceFlagApply_DefaultValueWithDestination(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{}) - expect(t, err, nil) - expect(t, defValue, dest) + assert.NoError(t, err) + assert.Equal(t, defValue, dest) } func TestUint64SliceFlagApply_ParentCommand(t *testing.T) { @@ -1452,11 +1393,7 @@ var float64FlagTests = []struct { func TestFloat64FlagHelpOutput(t *testing.T) { for _, test := range float64FlagTests { f := &FloatFlag{Name: test.name, Value: 0.1} - output := f.String() - - if output != test.expected { - t.Errorf("%q does not match %q", output, test.expected) - } + assert.Equal(t, test.expected, f.String()) } } @@ -1483,8 +1420,8 @@ func TestFloat64FlagApply_SetsAllNames(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--noodles", "1.3", "-N", "11", "--nurbles", "43.33333"}) - expect(t, err, nil) - expect(t, v, float64(43.33333)) + assert.NoError(t, err) + assert.Equal(t, float64(43.33333), v) } func TestFloat64FlagValueFromCommand(t *testing.T) { @@ -1514,11 +1451,7 @@ var float64SliceFlagTests = []struct { func TestFloat64SliceFlagHelpOutput(t *testing.T) { for _, test := range float64SliceFlagTests { fl := FloatSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value} - output := fl.String() - - if output != test.expected { - t.Errorf("%q does not match %q", output, test.expected) - } + assert.Equal(t, test.expected, fl.String()) } } @@ -1543,7 +1476,7 @@ func TestFloat64SliceFlagApply_SetsAllNames(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--bits", "23", "-B", "3", "--bips", "99"}) - expect(t, err, nil) + assert.NoError(t, err) } func TestFloat64SliceFlagApply_UsesEnvValues_noDefault(t *testing.T) { @@ -1556,8 +1489,8 @@ func TestFloat64SliceFlagApply_UsesEnvValues_noDefault(t *testing.T) { _ = fl.Apply(set) err := set.Parse(nil) - expect(t, err, nil) - expect(t, set.Lookup("goat").Value.(flag.Getter).Get().([]float64), []float64{1, 2}) + assert.NoError(t, err) + assert.Equal(t, []float64{1, 2}, set.Lookup("goat").Value.(flag.Getter).Get().([]float64)) } func TestFloat64SliceFlagApply_UsesEnvValues_withDefault(t *testing.T) { @@ -1569,8 +1502,8 @@ func TestFloat64SliceFlagApply_UsesEnvValues_withDefault(t *testing.T) { set := flag.NewFlagSet("test", 0) _ = fl.Apply(set) err := set.Parse(nil) - expect(t, err, nil) - expect(t, set.Lookup("goat").Value.(flag.Getter).Get().([]float64), []float64{1, 2}) + assert.NoError(t, err) + assert.Equal(t, []float64{1, 2}, set.Lookup("goat").Value.(flag.Getter).Get().([]float64)) } func TestFloat64SliceFlagApply_DefaultValueWithDestination(t *testing.T) { @@ -1582,8 +1515,8 @@ func TestFloat64SliceFlagApply_DefaultValueWithDestination(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{}) - expect(t, err, nil) - expect(t, defValue, dest) + assert.NoError(t, err) + assert.Equal(t, defValue, dest) } func TestFloat64SliceFlagValueFromCommand(t *testing.T) { @@ -1617,12 +1550,8 @@ func TestParseMultiString(t *testing.T) { &StringFlag{Name: "serve", Aliases: []string{"s"}}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.String("serve") != "10" { - t.Errorf("main name not set") - } - if cmd.String("s") != "10" { - t.Errorf("short name not set") - } + assert.Equal(t, "10", cmd.String("serve"), "main name not set") + assert.Equal(t, "10", cmd.String("s"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run", "-s", "10"}) @@ -1638,9 +1567,7 @@ func TestParseDestinationString(t *testing.T) { }, }, Action: func(context.Context, *Command) error { - if dest != "10" { - t.Errorf("expected destination String 10") - } + assert.Equal(t, "10", dest, "expected destination String 10") return nil }, }).Run(buildTestContext(t), []string{"run", "--dest", "10"}) @@ -1654,12 +1581,8 @@ func TestParseMultiStringFromEnv(t *testing.T) { &StringFlag{Name: "count", Aliases: []string{"c"}, Sources: EnvVars("APP_COUNT")}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.String("count") != "20" { - t.Errorf("main name not set") - } - if cmd.String("c") != "20" { - t.Errorf("short name not set") - } + assert.Equal(t, "20", cmd.String("count"), "main name not set") + assert.Equal(t, "20", cmd.String("c"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -1673,12 +1596,8 @@ func TestParseMultiStringFromEnvCascade(t *testing.T) { &StringFlag{Name: "count", Aliases: []string{"c"}, Sources: EnvVars("COMPAT_COUNT", "APP_COUNT")}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.String("count") != "20" { - t.Errorf("main name not set") - } - if cmd.String("c") != "20" { - t.Errorf("short name not set") - } + assert.Equal(t, "20", cmd.String("count"), "main name not set") + assert.Equal(t, "20", cmd.String("c"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -1691,12 +1610,8 @@ func TestParseMultiStringSlice(t *testing.T) { }, Action: func(_ context.Context, cmd *Command) error { expected := []string{"10", "20"} - if !reflect.DeepEqual(cmd.StringSlice("serve"), expected) { - t.Errorf("main name not set: %v != %v", expected, cmd.StringSlice("serve")) - } - if !reflect.DeepEqual(cmd.StringSlice("s"), expected) { - t.Errorf("short name not set: %v != %v", expected, cmd.StringSlice("s")) - } + assert.Equal(t, expected, cmd.StringSlice("serve"), "main name not set") + assert.Equal(t, expected, cmd.StringSlice("s"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"}) @@ -1709,12 +1624,8 @@ func TestParseMultiStringSliceWithDefaults(t *testing.T) { }, Action: func(_ context.Context, cmd *Command) error { expected := []string{"10", "20"} - if !reflect.DeepEqual(cmd.StringSlice("serve"), expected) { - t.Errorf("main name not set: %v != %v", expected, cmd.StringSlice("serve")) - } - if !reflect.DeepEqual(cmd.StringSlice("s"), expected) { - t.Errorf("short name not set: %v != %v", expected, cmd.StringSlice("s")) - } + assert.Equal(t, expected, cmd.StringSlice("serve"), "main name not set") + assert.Equal(t, expected, cmd.StringSlice("s"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"}) @@ -1729,12 +1640,7 @@ func TestParseMultiStringSliceWithDestination(t *testing.T) { }, Action: func(_ context.Context, cmd *Command) error { expected := []string{"10", "20"} - if !reflect.DeepEqual(dest, expected) { - t.Errorf("main name not set: %v != %v", expected, cmd.StringSlice("serve")) - } - if !reflect.DeepEqual(dest, expected) { - t.Errorf("short name not set: %v != %v", expected, cmd.StringSlice("s")) - } + assert.Equal(t, expected, dest, "destination val not set") return nil }, }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"}) @@ -1750,12 +1656,7 @@ func TestParseMultiStringSliceWithDestinationAndEnv(t *testing.T) { }, Action: func(_ context.Context, cmd *Command) error { expected := []string{"10", "20"} - if !reflect.DeepEqual(dest, expected) { - t.Errorf("main name not set: %v != %v", expected, cmd.StringSlice("serve")) - } - if !reflect.DeepEqual(dest, expected) { - t.Errorf("short name not set: %v != %v", expected, cmd.StringSlice("s")) - } + assert.Equal(t, expected, dest, "destination val not set") return nil }, }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"}) @@ -1773,12 +1674,7 @@ func TestParseMultiFloat64SliceWithDestinationAndEnv(t *testing.T) { }, Action: func(_ context.Context, cmd *Command) error { expected := []float64{10, 20} - if !reflect.DeepEqual(dest, expected) { - t.Errorf("main name not set: %v != %v", expected, cmd.StringSlice("serve")) - } - if !reflect.DeepEqual(dest, expected) { - t.Errorf("short name not set: %v != %v", expected, cmd.StringSlice("s")) - } + assert.Equal(t, expected, dest, "destination val not set") return nil }, }).Run(buildTestContext(t), []string{"run", "-s", "10", "-s", "20"}) @@ -1806,12 +1702,9 @@ func TestParseMultiStringSliceWithDefaultsUnset(t *testing.T) { &StringSliceFlag{Name: "serve", Aliases: []string{"s"}, Value: []string{"9", "2"}}, }, Action: func(_ context.Context, cmd *Command) error { - if !reflect.DeepEqual(cmd.StringSlice("serve"), []string{"9", "2"}) { - t.Errorf("main name not set: %v", cmd.StringSlice("serve")) - } - if !reflect.DeepEqual(cmd.StringSlice("s"), []string{"9", "2"}) { - t.Errorf("short name not set: %v", cmd.StringSlice("s")) - } + expected := []string{"9", "2"} + assert.Equal(t, expected, cmd.StringSlice("serve"), "main name not set") + assert.Equal(t, expected, cmd.StringSlice("s"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -1827,12 +1720,9 @@ func TestParseMultiStringSliceFromEnv(t *testing.T) { &StringSliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []string{}, Sources: EnvVars("APP_INTERVALS")}, }, Action: func(_ context.Context, cmd *Command) error { - if !reflect.DeepEqual(cmd.StringSlice("intervals"), []string{"20", "30", "40"}) { - t.Errorf("main name not set from env") - } - if !reflect.DeepEqual(cmd.StringSlice("i"), []string{"20", "30", "40"}) { - t.Errorf("short name not set from env") - } + expected := []string{"20", "30", "40"} + assert.Equal(t, expected, cmd.StringSlice("intervals"), "main name not set from env") + assert.Equal(t, expected, cmd.StringSlice("i"), "short name not set from env") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -1848,12 +1738,9 @@ func TestParseMultiStringSliceFromEnvWithDefaults(t *testing.T) { &StringSliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []string{"1", "2", "5"}, Sources: EnvVars("APP_INTERVALS")}, }, Action: func(_ context.Context, cmd *Command) error { - if !reflect.DeepEqual(cmd.StringSlice("intervals"), []string{"20", "30", "40"}) { - t.Errorf("main name not set from env") - } - if !reflect.DeepEqual(cmd.StringSlice("i"), []string{"20", "30", "40"}) { - t.Errorf("short name not set from env") - } + expected := []string{"20", "30", "40"} + assert.Equal(t, expected, cmd.StringSlice("intervals"), "main name not set from env") + assert.Equal(t, expected, cmd.StringSlice("i"), "short name not set from env") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -1869,12 +1756,9 @@ func TestParseMultiStringSliceFromEnvCascade(t *testing.T) { &StringSliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []string{}, Sources: EnvVars("COMPAT_INTERVALS", "APP_INTERVALS")}, }, Action: func(_ context.Context, cmd *Command) error { - if !reflect.DeepEqual(cmd.StringSlice("intervals"), []string{"20", "30", "40"}) { - t.Errorf("main name not set from env") - } - if !reflect.DeepEqual(cmd.StringSlice("i"), []string{"20", "30", "40"}) { - t.Errorf("short name not set from env") - } + expected := []string{"20", "30", "40"} + assert.Equal(t, expected, cmd.StringSlice("intervals"), "main name not set from env") + assert.Equal(t, expected, cmd.StringSlice("i"), "short name not set from env") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -1890,12 +1774,9 @@ func TestParseMultiStringSliceFromEnvCascadeWithDefaults(t *testing.T) { &StringSliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []string{"1", "2", "5"}, Sources: EnvVars("COMPAT_INTERVALS", "APP_INTERVALS")}, }, Action: func(_ context.Context, cmd *Command) error { - if !reflect.DeepEqual(cmd.StringSlice("intervals"), []string{"20", "30", "40"}) { - t.Errorf("main name not set from env") - } - if !reflect.DeepEqual(cmd.StringSlice("i"), []string{"20", "30", "40"}) { - t.Errorf("short name not set from env") - } + expected := []string{"20", "30", "40"} + assert.Equal(t, expected, cmd.StringSlice("intervals"), "main name not set from env") + assert.Equal(t, expected, cmd.StringSlice("i"), "short name not set from env") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -1912,12 +1793,7 @@ func TestParseMultiStringSliceFromEnvWithDestination(t *testing.T) { &StringSliceFlag{Name: "intervals", Aliases: []string{"i"}, Destination: &dest, Sources: EnvVars("APP_INTERVALS")}, }, Action: func(context.Context, *Command) error { - if !reflect.DeepEqual(dest, []string{"20", "30", "40"}) { - t.Errorf("main name not set from env") - } - if !reflect.DeepEqual(dest, []string{"20", "30", "40"}) { - t.Errorf("short name not set from env") - } + assert.Equal(t, []string{"20", "30", "40"}, dest, "destination value not set from env") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -1929,12 +1805,8 @@ func TestParseMultiInt(t *testing.T) { &IntFlag{Name: "serve", Aliases: []string{"s"}}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Int("serve") != 10 { - t.Errorf("main name not set") - } - if cmd.Int("s") != 10 { - t.Errorf("short name not set") - } + assert.Equal(t, int64(10), cmd.Int("serve"), "main name not set") + assert.Equal(t, int64(10), cmd.Int("s"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run", "-s", "10"}) @@ -1950,9 +1822,7 @@ func TestParseDestinationInt(t *testing.T) { }, }, Action: func(context.Context, *Command) error { - if dest != 10 { - t.Errorf("expected destination Int 10") - } + assert.Equal(t, int64(10), dest, "expected destination Int 10") return nil }, }).Run(buildTestContext(t), []string{"run", "--dest", "10"}) @@ -1967,12 +1837,8 @@ func TestParseMultiIntFromEnv(t *testing.T) { &IntFlag{Name: "timeout", Aliases: []string{"t"}, Sources: EnvVars("APP_TIMEOUT_SECONDS")}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Int("timeout") != 10 { - t.Errorf("main name not set") - } - if cmd.Int("t") != 10 { - t.Errorf("short name not set") - } + assert.Equal(t, int64(10), cmd.Int("timeout"), "main name not set") + assert.Equal(t, int64(10), cmd.Int("t"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -1985,12 +1851,8 @@ func TestParseMultiIntFromEnvCascade(t *testing.T) { &IntFlag{Name: "timeout", Aliases: []string{"t"}, Sources: EnvVars("COMPAT_TIMEOUT_SECONDS", "APP_TIMEOUT_SECONDS")}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Int("timeout") != 10 { - t.Errorf("main name not set") - } - if cmd.Int("t") != 10 { - t.Errorf("short name not set") - } + assert.Equal(t, int64(10), cmd.Int("timeout"), "main name not set") + assert.Equal(t, int64(10), cmd.Int("t"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -2034,12 +1896,9 @@ func TestParseMultiIntSliceWithDefaultsUnset(t *testing.T) { &IntSliceFlag{Name: "serve", Aliases: []string{"s"}, Value: []int64{9, 2}}, }, Action: func(_ context.Context, cmd *Command) error { - if !reflect.DeepEqual(cmd.IntSlice("serve"), []int64{9, 2}) { - t.Errorf("main name not set") - } - if !reflect.DeepEqual(cmd.IntSlice("s"), []int64{9, 2}) { - t.Errorf("short name not set") - } + expected := []int64{9, 2} + assert.Equal(t, expected, cmd.IntSlice("serve"), "main name not set") + assert.Equal(t, expected, cmd.IntSlice("s"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -2073,12 +1932,10 @@ func TestParseMultiIntSliceFromEnvWithDefaults(t *testing.T) { &IntSliceFlag{Name: "intervals", Aliases: []string{"i"}, Value: []int64{1, 2, 5}, Sources: EnvVars("APP_INTERVALS")}, }, Action: func(_ context.Context, cmd *Command) error { - if !reflect.DeepEqual(cmd.IntSlice("intervals"), []int64{20, 30, 40}) { - t.Errorf("main name not set from env") - } - if !reflect.DeepEqual(cmd.IntSlice("i"), []int64{20, 30, 40}) { - t.Errorf("short name not set from env") - } + r := require.New(t) + + r.Equalf([]int64{20, 30, 40}, cmd.IntSlice("intervals"), "main name not set from env") + r.Equalf([]int64{20, 30, 40}, cmd.IntSlice("i"), "short name not set from env") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -2108,12 +1965,8 @@ func TestParseMultiFloat64(t *testing.T) { &FloatFlag{Name: "serve", Aliases: []string{"s"}}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Float("serve") != 10.2 { - t.Errorf("main name not set") - } - if cmd.Float("s") != 10.2 { - t.Errorf("short name not set") - } + assert.Equal(t, 10.2, cmd.Float("serve"), "main name not set") + assert.Equal(t, 10.2, cmd.Float("s"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run", "-s", "10.2"}) @@ -2129,9 +1982,7 @@ func TestParseDestinationFloat64(t *testing.T) { }, }, Action: func(context.Context, *Command) error { - if dest != 10.2 { - t.Errorf("expected destination Float64 10.2") - } + assert.Equal(t, 10.2, dest, "expected destination Float64 10.2") return nil }, }).Run(buildTestContext(t), []string{"run", "--dest", "10.2"}) @@ -2144,12 +1995,8 @@ func TestParseMultiFloat64FromEnv(t *testing.T) { &FloatFlag{Name: "timeout", Aliases: []string{"t"}, Sources: EnvVars("APP_TIMEOUT_SECONDS")}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Float("timeout") != 15.5 { - t.Errorf("main name not set") - } - if cmd.Float("t") != 15.5 { - t.Errorf("short name not set") - } + assert.Equal(t, 15.5, cmd.Float("timeout"), "main name not set") + assert.Equal(t, 15.5, cmd.Float("t"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -2163,12 +2010,8 @@ func TestParseMultiFloat64FromEnvCascade(t *testing.T) { &FloatFlag{Name: "timeout", Aliases: []string{"t"}, Sources: EnvVars("COMPAT_TIMEOUT_SECONDS", "APP_TIMEOUT_SECONDS")}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Float("timeout") != 15.5 { - t.Errorf("main name not set") - } - if cmd.Float("t") != 15.5 { - t.Errorf("short name not set") - } + assert.Equal(t, 15.5, cmd.Float("timeout"), "main name not set") + assert.Equal(t, 15.5, cmd.Float("t"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -2208,12 +2051,8 @@ func TestParseMultiBool(t *testing.T) { &BoolFlag{Name: "serve", Aliases: []string{"s"}}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Bool("serve") != true { - t.Errorf("main name not set") - } - if cmd.Bool("s") != true { - t.Errorf("short name not set") - } + assert.True(t, cmd.Bool("serve"), "main name not set") + assert.True(t, cmd.Bool("s"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run", "--serve"}) @@ -2226,12 +2065,8 @@ func TestParseBoolShortOptionHandle(t *testing.T) { Name: "foobar", UseShortOptionHandling: true, Action: func(_ context.Context, cmd *Command) error { - if cmd.Bool("serve") != true { - t.Errorf("main name not set") - } - if cmd.Bool("option") != true { - t.Errorf("short name not set") - } + assert.True(t, cmd.Bool("serve"), "main name not set") + assert.True(t, cmd.Bool("option"), "short name not set") return nil }, Flags: []Flag{ @@ -2253,9 +2088,7 @@ func TestParseDestinationBool(t *testing.T) { }, }, Action: func(context.Context, *Command) error { - if dest != true { - t.Errorf("expected destination Bool true") - } + assert.True(t, dest, "expected destination Bool true") return nil }, }).Run(buildTestContext(t), []string{"run", "--dest"}) @@ -2268,12 +2101,8 @@ func TestParseMultiBoolFromEnv(t *testing.T) { &BoolFlag{Name: "debug", Aliases: []string{"d"}, Sources: EnvVars("APP_DEBUG")}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Bool("debug") != true { - t.Errorf("main name not set from env") - } - if cmd.Bool("d") != true { - t.Errorf("short name not set from env") - } + assert.True(t, cmd.Bool("debug"), "main name not set") + assert.True(t, cmd.Bool("d"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -2286,12 +2115,8 @@ func TestParseMultiBoolFromEnvCascade(t *testing.T) { &BoolFlag{Name: "debug", Aliases: []string{"d"}, Sources: EnvVars("COMPAT_DEBUG", "APP_DEBUG")}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Bool("debug") != true { - t.Errorf("main name not set from env") - } - if cmd.Bool("d") != true { - t.Errorf("short name not set from env") - } + assert.True(t, cmd.Bool("debug"), "main name not set from env") + assert.True(t, cmd.Bool("d"), "short name not set from env") return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -2316,12 +2141,8 @@ func TestParseBoolFromEnv(t *testing.T) { &BoolFlag{Name: "debug", Aliases: []string{"d"}, Sources: EnvVars("DEBUG")}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Bool("debug") != test.output { - t.Errorf("expected %+v to be parsed as %+v, instead was %+v", test.input, test.output, cmd.Bool("debug")) - } - if cmd.Bool("d") != test.output { - t.Errorf("expected %+v to be parsed as %+v, instead was %+v", test.input, test.output, cmd.Bool("d")) - } + assert.Equal(t, test.output, cmd.Bool("debug")) + assert.Equal(t, test.output, cmd.Bool("d")) return nil }, }).Run(buildTestContext(t), []string{"run"}) @@ -2335,12 +2156,8 @@ func TestParseMultiBoolT(t *testing.T) { &BoolFlag{Name: "implode", Aliases: []string{"i"}, Value: true}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Bool("implode") { - t.Errorf("main name not set") - } - if cmd.Bool("i") { - t.Errorf("short name not set") - } + assert.False(t, cmd.Bool("implode"), "main name not set") + assert.False(t, cmd.Bool("i"), "short name not set") return nil }, }).Run(buildTestContext(t), []string{"run", "--implode=false"}) @@ -2372,80 +2189,60 @@ func TestStringSlice_Serialized_Set(t *testing.T) { sl0 := NewStringSlice("a", "b") ser0 := sl0.Serialize() - if len(ser0) < len(slPfx) { - t.Fatalf("serialized shorter than expected: %q", ser0) - } + require.GreaterOrEqual(t, len(ser0), len(slPfx), "serialized shorter than expected") sl1 := NewStringSlice("c", "d") _ = sl1.Set(ser0) - if sl0.String() != sl1.String() { - t.Fatalf("pre and post serialization do not match: %v != %v", sl0, sl1) - } + require.Equal(t, sl0.String(), sl1.String(), "pre and post serialization do not match") } func TestIntSlice_Serialized_Set(t *testing.T) { sl0 := NewIntSlice(1, 2) ser0 := sl0.Serialize() - if len(ser0) < len(slPfx) { - t.Fatalf("serialized shorter than expected: %q", ser0) - } + require.GreaterOrEqual(t, len(ser0), len(slPfx), "serialized shorter than expected") sl1 := NewIntSlice(3, 4) _ = sl1.Set(ser0) - if sl0.String() != sl1.String() { - t.Fatalf("pre and post serialization do not match: %v != %v", sl0, sl1) - } + require.Equal(t, sl0.String(), sl1.String(), "pre and post serialization do not match") } func TestUintSlice_Serialized_Set(t *testing.T) { sl0 := NewUintSlice(1, 2) ser0 := sl0.Serialize() - if len(ser0) < len(slPfx) { - t.Fatalf("serialized shorter than expected: %q", ser0) - } + require.GreaterOrEqual(t, len(ser0), len(slPfx), "serialized shorter than expected") sl1 := NewUintSlice(3, 4) _ = sl1.Set(ser0) - if sl0.String() != sl1.String() { - t.Fatalf("pre and post serialization do not match: %v != %v", sl0, sl1) - } + require.Equal(t, sl0.String(), sl1.String(), "pre and post serialization do not match") } func TestUint64Slice_Serialized_Set(t *testing.T) { sl0 := NewUintSlice(1, 2) ser0 := sl0.Serialize() - if len(ser0) < len(slPfx) { - t.Fatalf("serialized shorter than expected: %q", ser0) - } + require.GreaterOrEqual(t, len(ser0), len(slPfx), "serialized shorter than expected") sl1 := NewUintSlice(3, 4) _ = sl1.Set(ser0) - if sl0.String() != sl1.String() { - t.Fatalf("pre and post serialization do not match: %v != %v", sl0, sl1) - } + require.Equal(t, sl0.String(), sl1.String(), "pre and post serialization do not match") } func TestStringMap_Serialized_Set(t *testing.T) { m0 := NewStringMap(map[string]string{"a": "b"}) ser0 := m0.Serialize() - if len(ser0) < len(slPfx) { - t.Fatalf("serialized shorter than expected: %q", ser0) - } + require.GreaterOrEqual(t, len(ser0), len(slPfx), "serialized shorter than expected") m1 := NewStringMap(map[string]string{"c": "d"}) _ = m1.Set(ser0) - if m0.String() != m1.String() { - t.Fatalf("pre and post serialization do not match: %v != %v", m0, m1) - } + require.Equal(t, m0.String(), m1.String(), "pre and post serialization do not match") } func TestTimestamp_set(t *testing.T) { @@ -2456,22 +2253,14 @@ func TestTimestamp_set(t *testing.T) { } time1 := "Feb 3, 2013 at 7:54pm (PST)" - if err := ts.Set(time1); err != nil { - t.Fatalf("Failed to parse time %s with layout %s", time1, ts.layout) - } - if ts.hasBeenSet == false { - t.Fatalf("hasBeenSet is not true after setting a time") - } + require.NoError(t, ts.Set(time1), "Failed to parse time %s with layout %s", time1, ts.layout) + require.True(t, ts.hasBeenSet, "hasBeenSet is not true after setting a time") ts.hasBeenSet = false ts.layout = time.RFC3339 time2 := "2006-01-02T15:04:05Z" - if err := ts.Set(time2); err != nil { - t.Fatalf("Failed to parse time %s with layout %s", time2, ts.layout) - } - if ts.hasBeenSet == false { - t.Fatalf("hasBeenSet is not true after setting a time") - } + require.NoError(t, ts.Set(time2), "Failed to parse time %s with layout %s", time2, ts.layout) + require.True(t, ts.hasBeenSet, "hasBeenSet is not true after setting a time") } func TestTimestampFlagApply(t *testing.T) { @@ -2481,8 +2270,8 @@ func TestTimestampFlagApply(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--time", "2006-01-02T15:04:05Z"}) - expect(t, err, nil) - expect(t, set.Lookup("time").Value.(flag.Getter).Get(), expectedResult) + assert.NoError(t, err) + assert.Equal(t, expectedResult, set.Lookup("time").Value.(flag.Getter).Get()) } func TestTimestampFlagApplyValue(t *testing.T) { @@ -2492,8 +2281,8 @@ func TestTimestampFlagApplyValue(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{""}) - expect(t, err, nil) - expect(t, set.Lookup("time").Value.(flag.Getter).Get(), expectedResult) + assert.NoError(t, err) + assert.Equal(t, expectedResult, set.Lookup("time").Value.(flag.Getter).Get()) } func TestTimestampFlagApply_Fail_Parse_Wrong_Layout(t *testing.T) { @@ -2503,7 +2292,7 @@ func TestTimestampFlagApply_Fail_Parse_Wrong_Layout(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--time", "2006-01-02T15:04:05Z"}) - expect(t, err, fmt.Errorf("invalid value \"2006-01-02T15:04:05Z\" for flag -time: parsing time \"2006-01-02T15:04:05Z\" as \"randomlayout\": cannot parse \"2006-01-02T15:04:05Z\" as \"randomlayout\"")) + assert.EqualError(t, err, "invalid value \"2006-01-02T15:04:05Z\" for flag -time: parsing time \"2006-01-02T15:04:05Z\" as \"randomlayout\": cannot parse \"2006-01-02T15:04:05Z\" as \"randomlayout\"") } func TestTimestampFlagApply_Fail_Parse_Wrong_Time(t *testing.T) { @@ -2513,7 +2302,7 @@ func TestTimestampFlagApply_Fail_Parse_Wrong_Time(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--time", "2006-01-02T15:04:05Z"}) - expect(t, err, fmt.Errorf("invalid value \"2006-01-02T15:04:05Z\" for flag -time: parsing time \"2006-01-02T15:04:05Z\" as \"Jan 2, 2006 at 3:04pm (MST)\": cannot parse \"2006-01-02T15:04:05Z\" as \"Jan\"")) + assert.EqualError(t, err, "invalid value \"2006-01-02T15:04:05Z\" for flag -time: parsing time \"2006-01-02T15:04:05Z\" as \"Jan 2, 2006 at 3:04pm (MST)\": cannot parse \"2006-01-02T15:04:05Z\" as \"Jan\"") } func TestTimestampFlagApply_Timezoned(t *testing.T) { @@ -2524,8 +2313,8 @@ func TestTimestampFlagApply_Timezoned(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--time", "Mon Jan 2 08:04:05 2006"}) - expect(t, err, nil) - expect(t, set.Lookup("time").Value.(flag.Getter).Get(), expectedResult.In(pdt)) + assert.NoError(t, err) + assert.Equal(t, expectedResult.In(pdt), set.Lookup("time").Value.(flag.Getter).Get()) } func TestTimestampFlagValueFromCommand(t *testing.T) { @@ -2595,16 +2384,12 @@ func TestFlagDefaultValue(t *testing.T) { expect: `--flag value [ --flag value ] (default: default1="default2")`, }, } - for i, v := range cases { + for _, v := range cases { set := flag.NewFlagSet("test", 0) set.SetOutput(io.Discard) _ = v.flag.Apply(set) - if err := set.Parse(v.toParse); err != nil { - t.Error(err) - } - if got := v.flag.String(); got != v.expect { - t.Errorf("TestFlagDefaultValue %d %s\nexpect:%s\ngot:%s", i, v.name, v.expect, got) - } + assert.NoError(t, set.Parse(v.toParse)) + assert.Equal(t, v.expect, v.flag.String()) } } @@ -2621,9 +2406,7 @@ func TestFlagDefaultValueWithEnv(t *testing.T) { os.Clearenv() ts, err := time.Parse(time.RFC3339, "2005-01-02T15:04:05Z") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) cases := []*flagDefaultTestCaseWithEnv{ { name: "stringSlice", @@ -2743,21 +2526,15 @@ func TestFlagDefaultValueWithEnv(t *testing.T) { }, }, } - for i, v := range cases { + for _, v := range cases { for key, val := range v.environ { os.Setenv(key, val) } set := flag.NewFlagSet("test", 0) set.SetOutput(io.Discard) - if err := v.flag.Apply(set); err != nil { - t.Fatal(err) - } - if err := set.Parse(v.toParse); err != nil { - t.Error(err) - } - if got := v.flag.String(); got != v.expect { - t.Errorf("TestFlagDefaultValue %d %s\nexpect:%s\ngot:%s", i, v.name, v.expect, got) - } + require.NoError(t, v.flag.Apply(set)) + require.NoError(t, set.Parse(v.toParse)) + assert.Equal(t, v.expect, v.flag.String()) } } @@ -2806,9 +2583,7 @@ func TestFlagValue(t *testing.T) { set := flag.NewFlagSet("test", 0) set.SetOutput(io.Discard) _ = v.flag.Apply(set) - if err := set.Parse(v.toParse); err != nil { - t.Error(err) - } + assert.NoError(t, set.Parse(v.toParse)) f := set.Lookup("flag") require.Equal(t, v.expect, f.Value.String()) }) @@ -2823,8 +2598,8 @@ func TestTimestampFlagApply_WithDestination(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--time", "2006-01-02T15:04:05Z"}) - expect(t, err, nil) - expect(t, destination, expectedResult) + assert.NoError(t, err) + assert.Equal(t, expectedResult, destination) } // Test issue #1254 @@ -2873,13 +2648,9 @@ func TestCustomizedSliceFlagSeparator(t *testing.T) { }() opts := []string{"opt1", "opt2", "opt3,op", "opt4"} ret := flagSplitMultiValues(strings.Join(opts, ";")) - if len(ret) != 4 { - t.Fatalf("split slice flag failed, want: 4, but get: %d", len(ret)) - } + require.Equal(t, 4, len(ret), "split slice flag failed") for idx, r := range ret { - if r != opts[idx] { - t.Fatalf("get %dth failed, wanted: %s, but get: %s", idx, opts[idx], r) - } + require.Equal(t, opts[idx], r, "get %dth failed", idx) } } @@ -2891,13 +2662,8 @@ func TestFlagSplitMultiValues_Disabled(t *testing.T) { opts := []string{"opt1", "opt2", "opt3,op", "opt4"} ret := flagSplitMultiValues(strings.Join(opts, defaultSliceFlagSeparator)) - if len(ret) != 1 { - t.Fatalf("failed to disable split slice flag, want: 1, but got: %d", len(ret)) - } - - if ret[0] != strings.Join(opts, defaultSliceFlagSeparator) { - t.Fatalf("failed to disable split slice flag, want: %s, but got: %s", strings.Join(opts, defaultSliceFlagSeparator), ret[0]) - } + require.Equal(t, 1, len(ret), "failed to disable split slice flag") + require.Equal(t, strings.Join(opts, defaultSliceFlagSeparator), ret[0]) } var stringMapFlagTests = []struct { @@ -2916,11 +2682,7 @@ var stringMapFlagTests = []struct { func TestStringMapFlagHelpOutput(t *testing.T) { for _, test := range stringMapFlagTests { f := &StringMapFlag{Name: test.name, Aliases: test.aliases, Value: test.value} - output := f.String() - - if output != test.expected { - t.Errorf("%q does not match %q", output, test.expected) - } + assert.Equal(t, test.expected, f.String()) } } @@ -2946,7 +2708,7 @@ func TestStringMapFlagApply_SetsAllNames(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--goat", "aaa=", "-G", "bbb=", "--gooots", "eeeee="}) - expect(t, err, nil) + assert.NoError(t, err) } func TestStringMapFlagApply_UsesEnvValues_noDefault(t *testing.T) { @@ -2959,9 +2721,9 @@ func TestStringMapFlagApply_UsesEnvValues_noDefault(t *testing.T) { _ = fl.Apply(set) err := set.Parse(nil) - expect(t, err, nil) - expect(t, val, map[string]string(nil)) - expect(t, set.Lookup("goat").Value.(flag.Getter).Get(), map[string]string{"vincent van goat": "scape goat"}) + assert.NoError(t, err) + assert.Nil(t, val) + assert.Equal(t, map[string]string{"vincent van goat": "scape goat"}, set.Lookup("goat").Value.(flag.Getter).Get()) } func TestStringMapFlagApply_UsesEnvValues_withDefault(t *testing.T) { @@ -2973,9 +2735,9 @@ func TestStringMapFlagApply_UsesEnvValues_withDefault(t *testing.T) { set := flag.NewFlagSet("test", 0) _ = fl.Apply(set) err := set.Parse(nil) - expect(t, err, nil) - expect(t, val, map[string]string{`some default`: `values here`}) - expect(t, set.Lookup("goat").Value.(flag.Getter).Get(), map[string]string{"vincent van goat": "scape goat"}) + assert.NoError(t, err) + assert.Equal(t, map[string]string{`some default`: `values here`}, val) + assert.Equal(t, map[string]string{"vincent van goat": "scape goat"}, set.Lookup("goat").Value.(flag.Getter).Get()) } func TestStringMapFlagApply_DefaultValueWithDestination(t *testing.T) { @@ -2986,8 +2748,8 @@ func TestStringMapFlagApply_DefaultValueWithDestination(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{}) - expect(t, err, nil) - expect(t, defValue, *fl.Destination) + assert.NoError(t, err) + assert.Equal(t, defValue, *fl.Destination) } func TestStringMapFlagValueFromCommand(t *testing.T) { @@ -3004,7 +2766,5 @@ func TestStringMapFlagApply_Error(t *testing.T) { _ = fl.Apply(set) err := set.Parse([]string{"--goat", "aaa", "bbb="}) - if err == nil { - t.Errorf("expected error, but got none") - } + assert.Error(t, err) } diff --git a/help_test.go b/help_test.go index 1b387ea768..141e978195 100644 --- a/help_test.go +++ b/help_test.go @@ -11,6 +11,7 @@ import ( "strings" "testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -83,9 +84,7 @@ func Test_Help_Custom_Flags(t *testing.T) { &BoolFlag{Name: "foo", Aliases: []string{"h"}}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Bool("h") != true { - t.Errorf("custom help flag not set") - } + assert.True(t, cmd.Bool("h"), "custom help flag not set") return nil }, Writer: out, @@ -131,9 +130,7 @@ func Test_Version_Custom_Flags(t *testing.T) { &BoolFlag{Name: "foo", Aliases: []string{"v"}}, }, Action: func(_ context.Context, cmd *Command) error { - if cmd.Bool("v") != true { - t.Errorf("custom version flag not set") - } + assert.True(t, cmd.Bool("v"), "custom version flag not set") return nil }, Writer: out, @@ -151,23 +148,13 @@ func Test_helpCommand_Action_ErrorIfNoTopic(t *testing.T) { _ = cmd.flagSet.Parse([]string{"foo"}) err := helpCommandAction(context.Background(), cmd) - - if err == nil { - t.Fatalf("expected error from helpCommandAction(), but got nil") - } + require.Error(t, err, "expected error from helpCommandAction()") exitErr, ok := err.(*exitError) - if !ok { - t.Fatalf("expected *exitError from helpCommandAction(), 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()) - } + require.True(t, ok, "expected *exitError from helpCommandAction()") - if exitErr.exitCode != 3 { - t.Fatalf("expected exit value = 3, got %d instead", exitErr.exitCode) - } + require.Contains(t, exitErr.Error(), "No help topic for", "expected an unknown help topic error") + require.Equal(t, 3, exitErr.exitCode, "expected exit value = 3") } func Test_helpCommand_InHelpOutput(t *testing.T) { @@ -179,13 +166,8 @@ func Test_helpCommand_InHelpOutput(t *testing.T) { s := output.String() - if strings.Contains(s, "\nCOMMANDS:\nGLOBAL OPTIONS:\n") { - t.Fatalf("empty COMMANDS section detected: %q", s) - } - - if !strings.Contains(s, "help, h") { - t.Fatalf("missing \"help, h\": %q", s) - } + require.NotContains(t, s, "\nCOMMANDS:\nGLOBAL OPTIONS:\n", "empty COMMANDS section detected") + require.Contains(t, s, "help, h", "missing \"help, h\"") } func TestHelpCommand_FullName(t *testing.T) { @@ -267,20 +249,16 @@ func Test_helpCommand_HideHelpCommand(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"app", "help", "help"}) - expect(t, err, nil) + assert.NoError(t, err) got := buf.String() notWant := "COMMANDS:" - if strings.Contains(got, notWant) { - t.Errorf("Not expected %q - Got %q", notWant, got) - } + assert.NotContains(t, got, notWant) } func Test_helpCommand_HideHelpFlag(t *testing.T) { app := buildMinimalTestCommand() - if err := app.Run(buildTestContext(t), []string{"app", "help", "-h"}); err == nil { - t.Errorf("Expected flag error - Got nil") - } + assert.Error(t, app.Run(buildTestContext(t), []string{"app", "help", "-h"}), "Expected flag error - Got nil") } func Test_helpSubcommand_Action_ErrorIfNoTopic(t *testing.T) { @@ -290,23 +268,13 @@ func Test_helpSubcommand_Action_ErrorIfNoTopic(t *testing.T) { _ = cmd.flagSet.Parse([]string{"foo"}) err := helpCommandAction(context.Background(), cmd) - - if err == nil { - t.Fatalf("expected error from helpCommandAction(), but got nil") - } + require.Error(t, err, "expected error from helpCommandAction(), but got nil") exitErr, ok := err.(*exitError) - if !ok { - t.Fatalf("expected *exitError from helpCommandAction(), but instead got: %v", err.Error()) - } + require.True(t, ok, "expected *exitError from helpCommandAction(), 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) - } + require.Contains(t, exitErr.Error(), "No help topic for", "expected an unknown help topic error") + require.Equal(t, 3, exitErr.exitCode, "unexpected exit value") } func TestShowAppHelp_CommandAliases(t *testing.T) { @@ -455,10 +423,7 @@ func TestShowCommandHelp_HelpPrinter(t *testing.T) { HelpPrinter = old }(HelpPrinter) HelpPrinter = func(w io.Writer, templ string, data interface{}) { - if templ != tt.wantTemplate { - t.Errorf("want template:\n%s\ngot template:\n%s", tt.wantTemplate, templ) - } - + assert.Equal(t, tt.wantTemplate, templ, "template mismatch") tt.printer(w, templ, data) } @@ -475,14 +440,10 @@ func TestShowCommandHelp_HelpPrinter(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"my-app", "help", tt.command}) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) got := buf.String() - if got != tt.wantOutput { - t.Errorf("want output %q, got %q", tt.wantOutput, got) - } + assert.Equal(t, tt.wantOutput, got) }) } } @@ -605,9 +566,7 @@ func TestShowSubcommandHelp_CommandAliases(t *testing.T) { _ = cmd.Run(buildTestContext(t), []string{"foo", "help"}) - if !strings.Contains(output.String(), "frobbly, fr, frob, bork") { - t.Errorf("expected output to include all command aliases; got: %q", output.String()) - } + assert.Contains(t, output.String(), "frobbly, fr, frob, bork", "expected output to include all command aliases") } func TestShowCommandHelp_Customtemplate(t *testing.T) { @@ -640,17 +599,14 @@ EXAMPLES: _ = cmd.Run(buildTestContext(t), []string{"foo", "help", "frobbly"}) - if strings.Contains(output.String(), "2. Frobbly runs without this param locally.") { - t.Errorf("expected output to exclude \"2. Frobbly runs without this param locally.\"; got: %q", output.String()) - } + assert.NotContains(t, output.String(), "2. Frobbly runs without this param locally.", + "expected output to exclude \"2. Frobbly runs without this param locally.\";") - if !strings.Contains(output.String(), "1. Frobbly runs with this param locally.") { - t.Errorf("expected output to include \"1. Frobbly runs with this param locally.\"; got: %q", output.String()) - } + assert.Contains(t, output.String(), "1. Frobbly runs with this param locally.", + "expected output to include \"1. Frobbly runs with this param locally.\"") - if !strings.Contains(output.String(), "$ foo frobbly wobbly") { - t.Errorf("expected output to include \"$ foo frobbly wobbly\"; got: %q", output.String()) - } + assert.Contains(t, output.String(), "$ foo frobbly wobbly", + "expected output to include \"$ foo frobbly wobbly\"") } func TestShowSubcommandHelp_CommandUsageText(t *testing.T) { @@ -668,9 +624,8 @@ func TestShowSubcommandHelp_CommandUsageText(t *testing.T) { _ = cmd.Run(buildTestContext(t), []string{"foo", "frobbly", "--help"}) - if !strings.Contains(output.String(), "this is usage text") { - t.Errorf("expected output to include usage text; got: %q", output.String()) - } + assert.Contains(t, output.String(), "this is usage text", + "expected output to include usage text") } func TestShowSubcommandHelp_MultiLine_CommandUsageText(t *testing.T) { @@ -698,9 +653,8 @@ UsageText`, UsageText ` - if !strings.Contains(output.String(), expected) { - t.Errorf("expected output to include usage text; got: %q", output.String()) - } + assert.Contains(t, output.String(), expected, + "expected output to include usage text") } func TestShowSubcommandHelp_SubcommandUsageText(t *testing.T) { @@ -723,9 +677,8 @@ func TestShowSubcommandHelp_SubcommandUsageText(t *testing.T) { _ = cmd.Run(buildTestContext(t), []string{"foo", "frobbly", "bobbly", "--help"}) - if !strings.Contains(output.String(), "this is usage text") { - t.Errorf("expected output to include usage text; got: %q", output.String()) - } + assert.Contains(t, output.String(), "this is usage text", + "expected output to include usage text") } func TestShowSubcommandHelp_MultiLine_SubcommandUsageText(t *testing.T) { @@ -758,9 +711,8 @@ UsageText`, UsageText ` - if !strings.Contains(output.String(), expected) { - t.Errorf("expected output to include usage text; got: %q", output.String()) - } + assert.Contains(t, output.String(), expected, + "expected output to include usage text") } func TestShowAppHelp_HiddenCommand(t *testing.T) { @@ -787,13 +739,11 @@ func TestShowAppHelp_HiddenCommand(t *testing.T) { _ = cmd.Run(buildTestContext(t), []string{"app", "--help"}) - if strings.Contains(output.String(), "secretfrob") { - t.Errorf("expected output to exclude \"secretfrob\"; got: %q", output.String()) - } + assert.NotContains(t, output.String(), "secretfrob", + "expected output to exclude \"secretfrob\"") - if !strings.Contains(output.String(), "frobbly") { - t.Errorf("expected output to include \"frobbly\"; got: %q", output.String()) - } + assert.Contains(t, output.String(), "frobbly", + "expected output to include \"frobbly\"") } func TestShowAppHelp_HelpPrinter(t *testing.T) { @@ -836,10 +786,7 @@ func TestShowAppHelp_HelpPrinter(t *testing.T) { HelpPrinter = old }(HelpPrinter) HelpPrinter = func(w io.Writer, templ string, data interface{}) { - if templ != tt.wantTemplate { - t.Errorf("want template:\n%s\ngot template:\n%s", tt.wantTemplate, templ) - } - + assert.Equal(t, tt.wantTemplate, templ, "unexpected template") tt.printer(w, templ, data) } @@ -851,14 +798,9 @@ func TestShowAppHelp_HelpPrinter(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"my-app", "help"}) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) - got := buf.String() - if got != tt.wantOutput { - t.Errorf("want output %q, got %q", tt.wantOutput, got) - } + assert.Equal(t, tt.wantOutput, buf.String()) }) } } @@ -903,14 +845,8 @@ func TestShowAppHelp_HelpPrinterCustom(t *testing.T) { HelpPrinterCustom = old }(HelpPrinterCustom) HelpPrinterCustom = func(w io.Writer, templ string, data interface{}, fm map[string]interface{}) { - if fm != nil { - t.Error("unexpected function map passed") - } - - if templ != tt.wantTemplate { - t.Errorf("want template:\n%s\ngot template:\n%s", tt.wantTemplate, templ) - } - + assert.Nil(t, fm, "unexpected function map passed") + assert.Equal(t, tt.wantTemplate, templ, "unexpected template") tt.printer(w, templ, data, fm) } @@ -922,14 +858,8 @@ func TestShowAppHelp_HelpPrinterCustom(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"my-app", "help"}) - if err != nil { - t.Fatal(err) - } - - got := buf.String() - if got != tt.wantOutput { - t.Errorf("want output %q, got %q", tt.wantOutput, got) - } + require.NoError(t, err) + assert.Equal(t, tt.wantOutput, buf.String()) }) } } @@ -984,13 +914,8 @@ VERSION: _ = cmd.Run(buildTestContext(t), []string{"app", "--help"}) - if strings.Contains(output.String(), "secretfrob") { - t.Errorf("expected output to exclude \"secretfrob\"; got: %q", output.String()) - } - - if !strings.Contains(output.String(), "frobbly") { - t.Errorf("expected output to include \"frobbly\"; got: %q", output.String()) - } + assert.NotContains(t, output.String(), "secretfrob", "expected output to exclude \"secretfrob\"") + assert.Contains(t, output.String(), "frobbly", "expected output to include \"frobbly\"") if !strings.Contains(output.String(), "PLATFORM:") || !strings.Contains(output.String(), "OS:") || @@ -1025,9 +950,7 @@ func TestShowAppHelp_UsageText(t *testing.T) { _ = cmd.Run(buildTestContext(t), []string{"foo"}) - if !strings.Contains(output.String(), "This is a single line of UsageText") { - t.Errorf("expected output to include usage text; got: %q", output.String()) - } + assert.Contains(t, output.String(), "This is a single line of UsageText", "expected output to include usage text") } func TestShowAppHelp_MultiLine_UsageText(t *testing.T) { @@ -1055,9 +978,7 @@ App UsageText`, App UsageText ` - if !strings.Contains(output.String(), expected) { - t.Errorf("expected output to include usage text; got: %q", output.String()) - } + assert.Contains(t, output.String(), expected, "expected output to include usage text") } func TestShowAppHelp_CommandMultiLine_UsageText(t *testing.T) { @@ -1091,9 +1012,7 @@ App UsageText`, " output, long usage output, long usage output\n" + " grobbly, grb1, grbb2 this is another long help output for the run command, long usage \n" + " output, long usage output" - if !strings.Contains(output.String(), expected) { - t.Errorf("expected output to include usage text; got: %q", output.String()) - } + assert.Contains(t, output.String(), expected, "expected output to include usage text") } func TestHideHelpCommand(t *testing.T) { @@ -1103,17 +1022,10 @@ func TestHideHelpCommand(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo", "help"}) - if err == nil { - t.Fatalf("expected a non-nil error") - } - if !strings.Contains(err.Error(), "No help topic for 'help'") { - t.Errorf("Run returned unexpected error: %v", err) - } + require.ErrorContains(t, err, "No help topic for 'help'") err = cmd.Run(buildTestContext(t), []string{"foo", "--help"}) - if err != nil { - t.Errorf("Run returned unexpected error: %v", err) - } + assert.NoError(t, err) } func TestHideHelpCommand_False(t *testing.T) { @@ -1123,14 +1035,10 @@ func TestHideHelpCommand_False(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo", "help"}) - if err != nil { - t.Errorf("Run returned unexpected error: %v", err) - } + assert.NoError(t, err) err = cmd.Run(buildTestContext(t), []string{"foo", "--help"}) - if err != nil { - t.Errorf("Run returned unexpected error: %v", err) - } + assert.NoError(t, err) } func TestHideHelpCommand_WithHideHelp(t *testing.T) { @@ -1141,20 +1049,10 @@ func TestHideHelpCommand_WithHideHelp(t *testing.T) { } err := cmd.Run(buildTestContext(t), []string{"foo", "help"}) - if err == nil { - t.Fatalf("expected a non-nil error") - } - if !strings.Contains(err.Error(), "No help topic for 'help'") { - t.Errorf("Run returned unexpected error: %v", err) - } + require.ErrorContains(t, err, "No help topic for 'help'") err = cmd.Run(buildTestContext(t), []string{"foo", "--help"}) - if err == nil { - t.Fatalf("expected a non-nil error") - } - if !strings.Contains(err.Error(), "flag: help requested") { - t.Errorf("Run returned unexpected error: %v", err) - } + require.ErrorContains(t, err, "flag: help requested") } func TestHideHelpCommand_WithSubcommands(t *testing.T) { @@ -1273,18 +1171,14 @@ func TestDefaultCompleteWithFlags(t *testing.T) { written := writer.String() - if written != tc.expected { - ct.Errorf("written help does not match expected %q != %q", written, tc.expected) - } + assert.Equal(t, tc.expected, written, "written help does not match") }) } } func TestWrap(t *testing.T) { emptywrap := wrap("", 4, 16) - if emptywrap != "" { - t.Errorf("Wrapping empty line should return empty line. Got '%s'.", emptywrap) - } + assert.Empty(t, emptywrap, "Wrapping empty line should return empty line") } func TestWrappedHelp(t *testing.T) { @@ -1373,10 +1267,7 @@ COPYRIGHT: ever read these things? ` - if output.String() != expected { - t.Errorf("Unexpected wrapping, got:\n%s\nexpected: %s", - output.String(), expected) - } + assert.Equal(t, expected, output.String(), "Unexpected wrapping") } func TestWrappedCommandHelp(t *testing.T) { @@ -1508,10 +1399,7 @@ OPTIONS: (default: false) ` - if output.String() != expected { - t.Errorf("Unexpected wrapping, got:\n%s\nexpected: %s", - output.String(), expected) - } + assert.Equal(t, expected, output.String(), "Unexpected wrapping") } func TestWrappedHelpSubcommand(t *testing.T) { diff --git a/helpers_test.go b/helpers_test.go index 9ecd8e18ae..d76e9def52 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -2,18 +2,8 @@ package cli import ( "os" - "reflect" - "testing" ) func init() { _ = os.Setenv("CLI_TEMPLATE_REPANIC", "1") } - -func expect(t *testing.T, a interface{}, b interface{}) { - t.Helper() - - if !reflect.DeepEqual(a, b) { - t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) - } -} diff --git a/sort_test.go b/sort_test.go index 662ef9b1cc..23cce96d0e 100644 --- a/sort_test.go +++ b/sort_test.go @@ -1,6 +1,10 @@ package cli -import "testing" +import ( + "testing" + + "github.com/stretchr/testify/assert" +) var lexicographicLessTests = []struct { i string @@ -23,8 +27,6 @@ var lexicographicLessTests = []struct { func TestLexicographicLess(t *testing.T) { for _, test := range lexicographicLessTests { actual := lexicographicLess(test.i, test.j) - if test.expected != actual { - t.Errorf(`expected string "%s" to come before "%s"`, test.i, test.j) - } + assert.Equal(t, test.expected, actual) } } diff --git a/suggestions_test.go b/suggestions_test.go index 103ba1c5c4..979fbe0cb4 100644 --- a/suggestions_test.go +++ b/suggestions_test.go @@ -4,6 +4,8 @@ import ( "errors" "fmt" "testing" + + "github.com/stretchr/testify/assert" ) func TestSuggestFlag(t *testing.T) { @@ -23,7 +25,7 @@ func TestSuggestFlag(t *testing.T) { res := suggestFlag(app.Flags, testCase.provided, false) // Then - expect(t, res, testCase.expected) + assert.Equal(t, testCase.expected, res) } } @@ -35,7 +37,7 @@ func TestSuggestFlagHideHelp(t *testing.T) { res := suggestFlag(app.Flags, "hlp", true) // Then - expect(t, res, "--fl") + assert.Equal(t, "--fl", res) } func TestSuggestFlagFromError(t *testing.T) { @@ -56,7 +58,7 @@ func TestSuggestFlagFromError(t *testing.T) { ) // Then - expect(t, res, fmt.Sprintf(SuggestDidYouMeanTemplate+"\n\n", testCase.expected)) + assert.Equal(t, fmt.Sprintf(SuggestDidYouMeanTemplate+"\n\n", testCase.expected), res) } } @@ -68,7 +70,7 @@ func TestSuggestFlagFromErrorWrongError(t *testing.T) { _, err := app.suggestFlagFromError(errors.New("invalid"), "") // Then - expect(t, true, err != nil) + assert.Error(t, err) } func TestSuggestFlagFromErrorWrongCommand(t *testing.T) { @@ -82,7 +84,7 @@ func TestSuggestFlagFromErrorWrongCommand(t *testing.T) { ) // Then - expect(t, true, err != nil) + assert.Error(t, err) } func TestSuggestFlagFromErrorNoSuggestion(t *testing.T) { @@ -96,7 +98,7 @@ func TestSuggestFlagFromErrorNoSuggestion(t *testing.T) { ) // Then - expect(t, true, err != nil) + assert.Error(t, err) } func TestSuggestCommand(t *testing.T) { @@ -118,6 +120,6 @@ func TestSuggestCommand(t *testing.T) { res := suggestCommand(app.Commands, testCase.provided) // Then - expect(t, res, testCase.expected) + assert.Equal(t, testCase.expected, res) } }