Ensure MultiError returned when both Before and After funcs given

main
Dan Buch 8 years ago
parent 61d4175525
commit 4cae17cfe1
No known key found for this signature in database
GPG Key ID: FAEF12936DD3E3EC

@ -196,11 +196,12 @@ func (a *App) Run(arguments []string) (err error) {
}
if a.Before != nil {
err = a.Before(context)
if err != nil {
fmt.Fprintf(a.Writer, "%v\n\n", err)
beforeErr := a.Before(context)
if beforeErr != nil {
fmt.Fprintf(a.Writer, "%v\n\n", beforeErr)
ShowAppHelp(context)
HandleExitCoder(err)
HandleExitCoder(beforeErr)
err = beforeErr
return err
}
}
@ -286,7 +287,7 @@ func (a *App) RunAsSubcommand(ctx *Context) (err error) {
if a.OnUsageError != nil {
err = a.OnUsageError(context, err, true)
HandleExitCoder(err)
return nil
return err
} else {
fmt.Fprintf(a.Writer, "%s\n\n", "Incorrect Usage.")
ShowSubcommandHelp(context)
@ -319,9 +320,10 @@ func (a *App) RunAsSubcommand(ctx *Context) (err error) {
}
if a.Before != nil {
err = a.Before(context)
if err != nil {
HandleExitCoder(err)
beforeErr := a.Before(context)
if beforeErr != nil {
HandleExitCoder(beforeErr)
err = beforeErr
return err
}
}

@ -522,6 +522,30 @@ func TestApp_BeforeFunc(t *testing.T) {
if counts.SubCommand != 0 {
t.Errorf("Subcommand executed when NOT expected")
}
// reset
counts = &opCounts{}
afterError := errors.New("fail again")
app.After = func(_ *Context) error {
return afterError
}
// run with the Before() func failing, wrapped by After()
err = app.Run([]string{"command", "--opt", "fail", "sub"})
// should be the same error produced by the Before func
if _, ok := err.(MultiError); !ok {
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")
}
}
func TestApp_AfterFunc(t *testing.T) {
@ -735,9 +759,10 @@ func TestApp_OrderOfOperations(t *testing.T) {
},
}
app.Action = func(c *Context) {
app.Action = func(c *Context) error {
counts.Total++
counts.Action = counts.Total
return nil
}
_ = app.Run([]string{"command", "--nope"})

@ -154,9 +154,10 @@ func TestContext_GlobalFlag(t *testing.T) {
app.Flags = []Flag{
StringFlag{Name: "global, g", Usage: "global"},
}
app.Action = func(c *Context) {
app.Action = func(c *Context) error {
globalFlag = c.GlobalString("global")
globalFlagSet = c.GlobalIsSet("global")
return nil
}
app.Run([]string{"command", "-g", "foo"})
expect(t, globalFlag, "foo")

Loading…
Cancel
Save