Repository navigation
Expand file tree
/
Copy pathexec_test.go
More file actions
92 lines (73 loc) · 2.53 KB
/
Copy pathexec_test.go
File metadata and controls
92 lines (73 loc) · 2.53 KB
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
package main
import (
"bufio"
"os/exec"
"syscall"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSignalKillTimeoutDefault(t *testing.T) {
assert.Equal(t, 10*time.Second, signalKillTimeout)
}
func TestSignalProcessWithTimeoutDeliversSignal(t *testing.T) {
t.Parallel()
cmd := exec.Command("sleep", "30")
require.NoError(t, cmd.Start())
signalProcessWithTimeout(cmd, syscall.SIGTERM)
require.NotNil(t, cmd.ProcessState)
status, ok := cmd.ProcessState.Sys().(syscall.WaitStatus)
require.True(t, ok)
assert.True(t, status.Signaled())
assert.Equal(t, syscall.SIGTERM, status.Signal())
}
func TestSignalProcessWithTimeoutKillsAfterTimeout(t *testing.T) {
// Not parallel: it overrides the package-level signalKillTimeout.
oldTimeout := signalKillTimeout
signalKillTimeout = 200 * time.Millisecond
t.Cleanup(func() { signalKillTimeout = oldTimeout })
// exec replaces the shell with sleep, so the ignored TERM disposition
// is inherited and SIGKILL is the only thing that stops it.
cmd := exec.Command("sh", "-c", `trap "" TERM; echo ready; exec sleep 30`)
stdout, err := cmd.StdoutPipe()
require.NoError(t, err)
require.NoError(t, cmd.Start())
// Wait until the trap is installed before signalling.
line, err := bufio.NewReader(stdout).ReadString('\n')
require.NoError(t, err)
require.Equal(t, "ready\n", line)
// Reap the process in our own goroutine: the kill branch returns without
// waiting, so reading ProcessState afterwards would race with cmd.Wait.
waitDone := make(chan struct{})
go func() {
_ = cmd.Wait()
close(waitDone)
}()
start := time.Now()
signalProcessWithTimeout(cmd, syscall.SIGTERM, waitDone)
assert.Less(t, time.Since(start), 2*time.Second)
select {
case <-waitDone:
case <-time.After(5 * time.Second):
t.Fatal("process was not killed after the timeout")
}
status, ok := cmd.ProcessState.Sys().(syscall.WaitStatus)
require.True(t, ok)
assert.True(t, status.Signaled())
assert.Equal(t, syscall.SIGKILL, status.Signal())
}
func TestSignalProcessWithTimeoutReturnsWhenAlreadyDone(t *testing.T) {
// Not parallel: it overrides the package-level signalKillTimeout.
oldTimeout := signalKillTimeout
signalKillTimeout = 5 * time.Second
t.Cleanup(func() { signalKillTimeout = oldTimeout })
cmd := exec.Command("sleep", "30")
require.NoError(t, cmd.Start())
waitDone := make(chan struct{})
close(waitDone)
start := time.Now()
signalProcessWithTimeout(cmd, syscall.SIGTERM, waitDone)
assert.Less(t, time.Since(start), time.Second)
_ = cmd.Wait()
}