Skip to content

Commit

Permalink
Add test for child flag value in Before hook
Browse files Browse the repository at this point in the history
  • Loading branch information
fjl committed Dec 6, 2024
1 parent 1e5ce5c commit 085f748
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1438,6 +1438,43 @@ func TestCommand_BeforeFunc(t *testing.T) {
assert.Zero(t, counts.SubCommand, "Subcommand executed when NOT expected")
}

func TestCommand_BeforeFuncPersistentFlag(t *testing.T) {
counts := &opCounts{}
beforeError := fmt.Errorf("fail")
var err error

cmd := &Command{
Before: func(_ context.Context, cmd *Command) (context.Context, error) {
counts.Before++
s := cmd.String("opt")
if s != "value" {
return nil, beforeError
}
return nil, nil
},
Commands: []*Command{
{
Name: "sub",
Action: func(context.Context, *Command) error {
counts.SubCommand++
return nil
},
},
},
Flags: []Flag{
&StringFlag{Name: "opt"},
},
Writer: io.Discard,
}

// Check that --opt value is available in root command Before hook,
// even when it was set on the subcommand.
err = cmd.Run(buildTestContext(t), []string{"command", "sub", "--opt", "value"})
require.NoError(t, err)
assert.Equal(t, 1, counts.Before, "Before() not executed when expected")
assert.Equal(t, 1, counts.SubCommand, "Subcommand not executed when expected")
}

func TestCommand_BeforeAfterFuncShellCompletion(t *testing.T) {
t.Skip("TODO: is '--generate-shell-completion' (flag) still supported?")

Expand Down

0 comments on commit 085f748

Please sign in to comment.