This repository has been archived by the owner on Feb 3, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathcmd_test.go
76 lines (64 loc) · 1.75 KB
/
cmd_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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package gps
import (
"context"
"fmt"
"os"
"os/exec"
"testing"
"time"
)
func mkTestCmd(iterations int) *monitoredCmd {
return newMonitoredCmd(
exec.Command("./echosleep", "-n", fmt.Sprint(iterations)),
500*time.Millisecond,
)
}
func TestMonitoredCmd(t *testing.T) {
// Sleeps and compile make this a bit slow
if testing.Short() {
t.Skip("skipping test with sleeps on short")
}
err := exec.Command("go", "build", "./_testdata/cmd/echosleep.go").Run()
if err != nil {
t.Errorf("Unable to build echosleep binary: %s", err)
}
defer os.Remove("./echosleep")
cmd := mkTestCmd(2)
err = cmd.run(context.Background())
if err != nil {
t.Errorf("Expected command not to fail: %s", err)
}
expectedOutput := "foo\nfoo\n"
if cmd.stdout.buf.String() != expectedOutput {
t.Errorf("Unexpected output:\n\t(GOT): %s\n\t(WNT): %s", cmd.stdout.buf.String(), expectedOutput)
}
cmd2 := mkTestCmd(10)
err = cmd2.run(context.Background())
if err == nil {
t.Error("Expected command to fail")
}
_, ok := err.(*timeoutError)
if !ok {
t.Errorf("Expected a timeout error, but got: %s", err)
}
expectedOutput = "foo\nfoo\nfoo\nfoo\n"
if cmd2.stdout.buf.String() != expectedOutput {
t.Errorf("Unexpected output:\n\t(GOT): %s\n\t(WNT): %s", cmd2.stdout.buf.String(), expectedOutput)
}
ctx, cancel := context.WithCancel(context.Background())
sync1, errchan := make(chan struct{}), make(chan error)
cmd3 := mkTestCmd(2)
go func() {
close(sync1)
errchan <- cmd3.run(ctx)
}()
// Make sure goroutine is at least started before we cancel the context.
<-sync1
// Give it a bit to get the process started.
<-time.After(5 * time.Millisecond)
cancel()
err = <-errchan
if err != context.Canceled {
t.Errorf("should have gotten canceled error, got %s", err)
}
}