1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
package process
import (
"errors"
"os/exec"
"sync"
"testing"
"time"
"github.com/hashicorp/go-gatedio"
"github.com/hashicorp/go-hclog"
)
func newManager() *Manager {
return NewManager(hclog.Default())
}
func TestExec_simple(t *testing.T) {
mgr := newManager()
out := gatedio.NewByteBuffer()
cmd := exec.Command("env")
cmd.Stdout = out
err := mgr.Exec(cmd)
if err != nil {
t.Errorf("expected %q to be nil", err)
}
output := out.String()
if output == "" {
t.Error("expected output from running 'env', got empty string")
}
}
func TestClose(t *testing.T) {
mgr := newManager()
wg := sync.WaitGroup{}
tasks := 4
errors := make([]error, tasks)
start := time.Now()
for i := 0; i < tasks; i++ {
wg.Add(1)
go func(index int) {
cmd := exec.Command("sleep", "0.5")
err := mgr.Exec(cmd)
if err != nil {
errors[index] = err
}
wg.Done()
}(i)
}
// let processes kick off
time.Sleep(50 * time.Millisecond)
mgr.Close()
end := time.Now()
wg.Wait()
duration := end.Sub(start)
if duration >= 500*time.Millisecond {
t.Errorf("expected to close, total time was %q", duration)
}
for _, err := range errors {
if err != ErrClosing {
t.Errorf("expected manager closing error, found %q", err)
}
}
}
func TestClose_alreadyClosed(t *testing.T) {
mgr := newManager()
mgr.Close()
// repeated closing does not error
mgr.Close()
err := mgr.Exec(exec.Command("sleep", "1"))
if err != ErrClosing {
t.Errorf("expected manager closing error, found %q", err)
}
}
func TestExitCode(t *testing.T) {
mgr := newManager()
err := mgr.Exec(exec.Command("ls", "doesnotexist"))
exitErr := &ChildExit{}
if !errors.As(err, &exitErr) {
t.Errorf("expected a ChildExit err, got %q", err)
}
if exitErr.ExitCode == 0 {
t.Error("expected non-zero exit code , got 0")
}
}
|