Skip to content

Commit

Permalink
Use background context instead of nil
Browse files Browse the repository at this point in the history
  • Loading branch information
burdiyan committed Jul 3, 2019
1 parent 4a478f0 commit d360eef
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
6 changes: 5 additions & 1 deletion command.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ type Command struct {
}

// Context returns underlying command context. If command wasn't
// executed with ExecuteContext the returned context will be nil.
// executed with ExecuteContext Context returns Background context.
func (c *Command) Context() context.Context {
return c.ctx
}
Expand Down Expand Up @@ -883,6 +883,10 @@ func (c *Command) Execute() error {

// ExecuteC executes the command.
func (c *Command) ExecuteC() (cmd *Command, err error) {
if c.ctx == nil {
c.ctx = context.Background()
}

// Regardless of what command execute is called on, run on Root only
if c.HasParent() {
return c.Root().ExecuteC()
Expand Down
29 changes: 28 additions & 1 deletion command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ func TestSubcommandExecuteC(t *testing.T) {
}

func TestExecuteContext(t *testing.T) {
ctx := context.Background()
ctx := context.TODO()

ctxRun := func(cmd *Command, args []string) {
if cmd.Context() != ctx {
Expand Down Expand Up @@ -175,6 +175,33 @@ func TestExecuteContext(t *testing.T) {
}
}

func TestExecute_NoContext(t *testing.T) {
run := func(cmd *Command, args []string) {
if cmd.Context() != context.Background() {
t.Errorf("Command %s must have background context", cmd.Use)
}
}

rootCmd := &Command{Use: "root", Run: run, PreRun: run}
childCmd := &Command{Use: "child", Run: run, PreRun: run}
granchildCmd := &Command{Use: "grandchild", Run: run, PreRun: run}

childCmd.AddCommand(granchildCmd)
rootCmd.AddCommand(childCmd)

if _, err := executeCommand(rootCmd, ""); err != nil {
t.Errorf("Root command must not fail: %+v", err)
}

if _, err := executeCommand(rootCmd, "child"); err != nil {
t.Errorf("Subcommand must not fail: %+v", err)
}

if _, err := executeCommand(rootCmd, "child", "grandchild"); err != nil {
t.Errorf("Command child must not fail: %+v", err)
}
}

func TestRootUnknownCommandSilenced(t *testing.T) {
rootCmd := &Command{Use: "root", Run: emptyRun}
rootCmd.SilenceErrors = true
Expand Down

0 comments on commit d360eef

Please sign in to comment.