Skip to content

Commit 085f748

Browse files
committed
Add test for child flag value in Before hook
1 parent 1e5ce5c commit 085f748

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

command_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1438,6 +1438,43 @@ func TestCommand_BeforeFunc(t *testing.T) {
14381438
assert.Zero(t, counts.SubCommand, "Subcommand executed when NOT expected")
14391439
}
14401440

1441+
func TestCommand_BeforeFuncPersistentFlag(t *testing.T) {
1442+
counts := &opCounts{}
1443+
beforeError := fmt.Errorf("fail")
1444+
var err error
1445+
1446+
cmd := &Command{
1447+
Before: func(_ context.Context, cmd *Command) (context.Context, error) {
1448+
counts.Before++
1449+
s := cmd.String("opt")
1450+
if s != "value" {
1451+
return nil, beforeError
1452+
}
1453+
return nil, nil
1454+
},
1455+
Commands: []*Command{
1456+
{
1457+
Name: "sub",
1458+
Action: func(context.Context, *Command) error {
1459+
counts.SubCommand++
1460+
return nil
1461+
},
1462+
},
1463+
},
1464+
Flags: []Flag{
1465+
&StringFlag{Name: "opt"},
1466+
},
1467+
Writer: io.Discard,
1468+
}
1469+
1470+
// Check that --opt value is available in root command Before hook,
1471+
// even when it was set on the subcommand.
1472+
err = cmd.Run(buildTestContext(t), []string{"command", "sub", "--opt", "value"})
1473+
require.NoError(t, err)
1474+
assert.Equal(t, 1, counts.Before, "Before() not executed when expected")
1475+
assert.Equal(t, 1, counts.SubCommand, "Subcommand not executed when expected")
1476+
}
1477+
14411478
func TestCommand_BeforeAfterFuncShellCompletion(t *testing.T) {
14421479
t.Skip("TODO: is '--generate-shell-completion' (flag) still supported?")
14431480

0 commit comments

Comments
 (0)