Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/common-go/process/process_test.go
2498 views
1
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package process
6
7
import (
8
"context"
9
"fmt"
10
"io/ioutil"
11
"os"
12
"os/exec"
13
"syscall"
14
"testing"
15
"time"
16
17
"github.com/stretchr/testify/require"
18
"golang.org/x/sys/unix"
19
)
20
21
func TestTerminateSync(t *testing.T) {
22
cmd := exec.Command("/bin/sleep", "20")
23
require.NoError(t, cmd.Start())
24
require.NotNil(t, cmd.Process)
25
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
26
defer cancel()
27
err := TerminateSync(ctx, cmd.Process.Pid)
28
require.NoError(t, err)
29
require.Equal(t, os.ErrProcessDone, cmd.Process.Signal(unix.SIGHUP))
30
}
31
32
func TestTerminateSync_ignoring_process(t *testing.T) {
33
34
tests := []struct {
35
processTimeSeconds int
36
gracePeriod time.Duration
37
fileExists bool
38
}{
39
{
40
processTimeSeconds: 1,
41
gracePeriod: 7 * time.Second,
42
fileExists: true,
43
},
44
{
45
processTimeSeconds: 7,
46
gracePeriod: time.Second,
47
fileExists: false,
48
},
49
{
50
processTimeSeconds: 0,
51
gracePeriod: 5 * time.Second,
52
fileExists: true,
53
},
54
}
55
for _, test := range tests {
56
dir, err := ioutil.TempDir("", "terminal_test_close")
57
require.NoError(t, err)
58
expectedFile := dir + "/done.txt"
59
script := dir + "/script.sh"
60
err = ioutil.WriteFile(script, []byte(fmt.Sprintf(`#!/bin/bash
61
trap 'echo \"Be patient\"' SIGTERM SIGINT SIGHUP
62
for ((n= %d ; n; n--))
63
do
64
sleep 1
65
done
66
echo touching
67
touch %s
68
echo touched
69
`, test.processTimeSeconds, expectedFile)), 0644)
70
require.NoError(t, err)
71
72
cmd := exec.Command("/bin/bash", script)
73
74
cmd.Stdout = os.Stdout
75
cmd.Stderr = os.Stderr
76
require.NoError(t, cmd.Start())
77
require.NotNil(t, cmd.Process)
78
time.Sleep(100 * time.Millisecond)
79
require.NotEqual(t, os.ErrProcessDone, cmd.Process.Signal(syscall.Signal(0)))
80
ctx, cancel := context.WithTimeout(context.Background(), test.gracePeriod)
81
defer cancel()
82
err = TerminateSync(ctx, cmd.Process.Pid)
83
if test.fileExists {
84
require.NoError(t, err)
85
require.FileExists(t, expectedFile)
86
} else {
87
require.Equal(t, ErrForceKilled, err)
88
require.NoFileExists(t, expectedFile)
89
}
90
}
91
}
92
93