-
Notifications
You must be signed in to change notification settings - Fork 7
/
command_test.go
61 lines (54 loc) · 1.46 KB
/
command_test.go
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
package proclimit
import (
"bytes"
"github.com/friendsofgo/errors"
"os/exec"
"testing"
)
func echo(args ...string) *exec.Cmd {
return exec.Command("echo", args...)
}
type spyLimiter struct {
calledWithPid int
returnErr error
}
func (s *spyLimiter) Limit(pid int) error {
s.calledWithPid = pid
return s.returnErr
}
func TestCmdStartInvokesLimit(t *testing.T) {
sl := &spyLimiter{}
cmd := &Cmd{Cmd: echo(), Limiter: sl}
err := cmd.Start()
if err != nil {
t.Fatalf("expected no error, but got: %v", err)
}
if sl.calledWithPid != cmd.Process.Pid {
t.Errorf("expected pid %d to be limited, but got %d", cmd.Process.Pid, sl.calledWithPid)
}
}
func TestCmdStartLimiterErrors(t *testing.T) {
sl := &spyLimiter{returnErr: errors.New("limit error")}
cmd := &Cmd{Cmd: echo(), Limiter: sl}
err := cmd.Start()
if err == nil || errors.Cause(err) != sl.returnErr {
t.Errorf("expected error \"%v\", but got: %v", sl.returnErr, err)
}
s, err := cmd.Process.Wait()
if err != nil {
t.Fatalf("failed to wait for process: %v", err)
}
if s.ExitCode() != -1 {
t.Errorf("expected exit code -1 (terminated by signal), but got: %d", s.ExitCode())
}
}
func TestCmdOutput(t *testing.T) {
cmd := &Cmd{Cmd: echo("hello, world!"), Limiter: &spyLimiter{}}
out, err := cmd.Output()
if err != nil {
t.Fatalf("expected no error, but got: %v", err)
}
if !bytes.Equal(out, []byte("hello, world!\n")) {
t.Errorf("expected 'hello, world!\\n', but got: '%s'", string(out))
}
}