File tree Expand file tree Collapse file tree 2 files changed +20
-6
lines changed
Expand file tree Collapse file tree 2 files changed +20
-6
lines changed Original file line number Diff line number Diff line change @@ -145,7 +145,12 @@ func WithEnvironmentVariables(env EnvVars) func(c *Command) {
145145 }
146146}
147147
148+ // WithContext adds context.Context to the command. Context timeout/deadline
149+ // is favored over Timeout
148150func WithContext (ctx context.Context ) func (c * Command ) {
151+ if ctx == nil {
152+ panic ("nil context" )
153+ }
149154 return func (c * Command ) {
150155 c .ctx = ctx
151156 }
@@ -219,10 +224,7 @@ func (c *Command) Execute() error {
219224
220225 done := make (chan error , 1 )
221226 go func () {
222- select {
223- case done <- cmd .Wait ():
224- return
225- }
227+ done <- cmd .Wait ()
226228 }()
227229
228230 select {
@@ -239,7 +241,6 @@ func (c *Command) Execute() error {
239241 c .getExitCode (err )
240242 }
241243 }
242-
243244 c .executed = true
244245 return nil
245246}
Original file line number Diff line number Diff line change @@ -2,12 +2,14 @@ package cmd
22
33import (
44 "bytes"
5+ "context"
56 "fmt"
6- "github.com/stretchr/testify/assert"
77 "os"
88 "runtime"
99 "testing"
1010 "time"
11+
12+ "github.com/stretchr/testify/assert"
1113)
1214
1315func TestCommand_NewCommand (t * testing.T ) {
@@ -129,3 +131,14 @@ func TestCommand_SetOptions(t *testing.T) {
129131 assert .Equal (t , time .Duration (1000000000 ), c .Timeout )
130132 assertEqualWithLineBreak (t , "test" , writer .String ())
131133}
134+
135+ func TestCommand_WithContext (t * testing.T ) {
136+ ctx , cancel := context .WithTimeout (context .Background (), 2 * time .Second )
137+ defer cancel ()
138+ // WithContext is favored over Timeout
139+ cmd := NewCommand ("sleep 3;" , WithContext (ctx ), WithTimeout (1 * time .Second ))
140+
141+ err := cmd .Execute ()
142+ assert .NotNil (t , err )
143+ assert .Equal (t , "context deadline exceeded" , err .Error ())
144+ }
You can’t perform that action at this time.
0 commit comments