Path: blob/main/components/common-go/process/process_test.go
2498 views
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package process56import (7"context"8"fmt"9"io/ioutil"10"os"11"os/exec"12"syscall"13"testing"14"time"1516"github.com/stretchr/testify/require"17"golang.org/x/sys/unix"18)1920func TestTerminateSync(t *testing.T) {21cmd := exec.Command("/bin/sleep", "20")22require.NoError(t, cmd.Start())23require.NotNil(t, cmd.Process)24ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)25defer cancel()26err := TerminateSync(ctx, cmd.Process.Pid)27require.NoError(t, err)28require.Equal(t, os.ErrProcessDone, cmd.Process.Signal(unix.SIGHUP))29}3031func TestTerminateSync_ignoring_process(t *testing.T) {3233tests := []struct {34processTimeSeconds int35gracePeriod time.Duration36fileExists bool37}{38{39processTimeSeconds: 1,40gracePeriod: 7 * time.Second,41fileExists: true,42},43{44processTimeSeconds: 7,45gracePeriod: time.Second,46fileExists: false,47},48{49processTimeSeconds: 0,50gracePeriod: 5 * time.Second,51fileExists: true,52},53}54for _, test := range tests {55dir, err := ioutil.TempDir("", "terminal_test_close")56require.NoError(t, err)57expectedFile := dir + "/done.txt"58script := dir + "/script.sh"59err = ioutil.WriteFile(script, []byte(fmt.Sprintf(`#!/bin/bash60trap 'echo \"Be patient\"' SIGTERM SIGINT SIGHUP61for ((n= %d ; n; n--))62do63sleep 164done65echo touching66touch %s67echo touched68`, test.processTimeSeconds, expectedFile)), 0644)69require.NoError(t, err)7071cmd := exec.Command("/bin/bash", script)7273cmd.Stdout = os.Stdout74cmd.Stderr = os.Stderr75require.NoError(t, cmd.Start())76require.NotNil(t, cmd.Process)77time.Sleep(100 * time.Millisecond)78require.NotEqual(t, os.ErrProcessDone, cmd.Process.Signal(syscall.Signal(0)))79ctx, cancel := context.WithTimeout(context.Background(), test.gracePeriod)80defer cancel()81err = TerminateSync(ctx, cmd.Process.Pid)82if test.fileExists {83require.NoError(t, err)84require.FileExists(t, expectedFile)85} else {86require.Equal(t, ErrForceKilled, err)87require.NoFileExists(t, expectedFile)88}89}90}919293