MCPcopy
hub / github.com/urfave/cli / TestCommand_BeforeFunc

Function TestCommand_BeforeFunc

command_test.go:1587–1655  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

1585}
1586
1587func TestCommand_BeforeFunc(t *testing.T) {
1588 counts := &opCounts{}
1589 beforeError := fmt.Errorf("fail")
1590 var err error
1591
1592 cmd := &Command{
1593 Before: func(_ context.Context, cmd *Command) (context.Context, error) {
1594 counts.Total++
1595 counts.Before = counts.Total
1596 s := cmd.String("opt")
1597 if s == "fail" {
1598 return nil, beforeError
1599 }
1600
1601 return nil, nil
1602 },
1603 Commands: []*Command{
1604 {
1605 Name: "sub",
1606 Action: func(context.Context, *Command) error {
1607 counts.Total++
1608 counts.SubCommand = counts.Total
1609 return nil
1610 },
1611 },
1612 },
1613 Flags: []Flag{
1614 &StringFlag{Name: "opt"},
1615 },
1616 Writer: io.Discard,
1617 }
1618
1619 // run with the Before() func succeeding
1620 err = cmd.Run(buildTestContext(t), []string{"command", "--opt", "succeed", "sub"})
1621 require.NoError(t, err)
1622
1623 assert.Equal(t, 1, counts.Before, "Before() not executed when expected")
1624 assert.Equal(t, 2, counts.SubCommand, "Subcommand not executed when expected")
1625
1626 // reset
1627 counts = &opCounts{}
1628
1629 // run with the Before() func failing
1630 err = cmd.Run(buildTestContext(t), []string{"command", "--opt", "fail", "sub"})
1631
1632 // should be the same error produced by the Before func
1633 assert.ErrorIs(t, err, beforeError, "Run error expected, but not received")
1634 assert.Equal(t, 1, counts.Before, "Before() not executed when expected")
1635 assert.Equal(t, 0, counts.SubCommand, "Subcommand executed when NOT expected")
1636
1637 // reset
1638 counts = &opCounts{}
1639
1640 afterError := errors.New("fail again")
1641 cmd.After = func(context.Context, *Command) error {
1642 return afterError
1643 }
1644

Callers

nothing calls this directly

Calls 3

StringMethod · 0.95
RunMethod · 0.95
buildTestContextFunction · 0.85

Tested by

no test coverage detected