github.com/ttys3/engine@v17.12.1-ce-rc2+incompatible/pkg/signal/trap_linux_test.go (about)

     1  // +build linux
     2  
     3  package signal
     4  
     5  import (
     6  	"fmt"
     7  	"io/ioutil"
     8  	"os"
     9  	"os/exec"
    10  	"syscall"
    11  	"testing"
    12  
    13  	"github.com/stretchr/testify/assert"
    14  	"github.com/stretchr/testify/require"
    15  )
    16  
    17  func buildTestBinary(t *testing.T, tmpdir string, prefix string) (string, string) {
    18  	tmpDir, err := ioutil.TempDir(tmpdir, prefix)
    19  	require.NoError(t, err)
    20  	exePath := tmpDir + "/" + prefix
    21  	wd, _ := os.Getwd()
    22  	testHelperCode := wd + "/testfiles/main.go"
    23  	cmd := exec.Command("go", "build", "-o", exePath, testHelperCode)
    24  	err = cmd.Run()
    25  	require.NoError(t, err)
    26  	return exePath, tmpDir
    27  }
    28  
    29  func TestTrap(t *testing.T) {
    30  	var sigmap = []struct {
    31  		name     string
    32  		signal   os.Signal
    33  		multiple bool
    34  	}{
    35  		{"TERM", syscall.SIGTERM, false},
    36  		{"QUIT", syscall.SIGQUIT, true},
    37  		{"INT", os.Interrupt, false},
    38  		{"TERM", syscall.SIGTERM, true},
    39  		{"INT", os.Interrupt, true},
    40  	}
    41  	exePath, tmpDir := buildTestBinary(t, "", "main")
    42  	defer os.RemoveAll(tmpDir)
    43  
    44  	for _, v := range sigmap {
    45  		cmd := exec.Command(exePath)
    46  		cmd.Env = append(os.Environ(), fmt.Sprintf("SIGNAL_TYPE=%s", v.name))
    47  		if v.multiple {
    48  			cmd.Env = append(cmd.Env, "IF_MULTIPLE=1")
    49  		}
    50  		err := cmd.Start()
    51  		require.NoError(t, err)
    52  		err = cmd.Wait()
    53  		if e, ok := err.(*exec.ExitError); ok {
    54  			code := e.Sys().(syscall.WaitStatus).ExitStatus()
    55  			if v.multiple {
    56  				assert.Equal(t, 128+int(v.signal.(syscall.Signal)), code)
    57  			} else {
    58  				assert.Equal(t, 99, code)
    59  			}
    60  			continue
    61  		}
    62  		t.Fatal("process didn't end with any error")
    63  	}
    64  
    65  }
    66  
    67  func TestDumpStacks(t *testing.T) {
    68  	directory, err := ioutil.TempDir("", "test-dump-tasks")
    69  	assert.NoError(t, err)
    70  	defer os.RemoveAll(directory)
    71  	dumpPath, err := DumpStacks(directory)
    72  	assert.NoError(t, err)
    73  	readFile, _ := ioutil.ReadFile(dumpPath)
    74  	fileData := string(readFile)
    75  	assert.Contains(t, fileData, "goroutine")
    76  }
    77  
    78  func TestDumpStacksWithEmptyInput(t *testing.T) {
    79  	path, err := DumpStacks("")
    80  	assert.NoError(t, err)
    81  	assert.Equal(t, os.Stderr.Name(), path)
    82  }