github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/pkg/signal/trap_linux_test.go (about)

     1  // +build linux
     2  
     3  package signal // import "github.com/demonoid81/moby/pkg/signal"
     4  
     5  import (
     6  	"io/ioutil"
     7  	"os"
     8  	"os/exec"
     9  	"syscall"
    10  	"testing"
    11  
    12  	"gotest.tools/v3/assert"
    13  	is "gotest.tools/v3/assert/cmp"
    14  )
    15  
    16  func buildTestBinary(t *testing.T, tmpdir string, prefix string) (string, string) {
    17  	t.Helper()
    18  	tmpDir, err := ioutil.TempDir(tmpdir, prefix)
    19  	assert.NilError(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  	assert.NilError(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  		t.Run(v.name, func(t *testing.T) {
    46  			cmd := exec.Command(exePath)
    47  			cmd.Env = append(os.Environ(), "SIGNAL_TYPE="+v.name)
    48  			if v.multiple {
    49  				cmd.Env = append(cmd.Env, "IF_MULTIPLE=1")
    50  			}
    51  			err := cmd.Start()
    52  			assert.NilError(t, err)
    53  			err = cmd.Wait()
    54  			e, ok := err.(*exec.ExitError)
    55  			assert.Assert(t, ok, "expected exec.ExitError, got %T", e)
    56  
    57  			code := e.Sys().(syscall.WaitStatus).ExitStatus()
    58  			if v.multiple {
    59  				assert.Check(t, is.DeepEqual(128+int(v.signal.(syscall.Signal)), code))
    60  			} else {
    61  				assert.Check(t, is.Equal(99, code))
    62  			}
    63  		})
    64  	}
    65  
    66  }
    67  
    68  func TestDumpStacks(t *testing.T) {
    69  	directory, err := ioutil.TempDir("", "test-dump-tasks")
    70  	assert.Check(t, err)
    71  	defer os.RemoveAll(directory)
    72  	dumpPath, err := DumpStacks(directory)
    73  	assert.Check(t, err)
    74  	readFile, _ := ioutil.ReadFile(dumpPath)
    75  	fileData := string(readFile)
    76  	assert.Check(t, is.Contains(fileData, "goroutine"))
    77  }
    78  
    79  func TestDumpStacksWithEmptyInput(t *testing.T) {
    80  	path, err := DumpStacks("")
    81  	assert.Check(t, err)
    82  	assert.Check(t, is.Equal(os.Stderr.Name(), path))
    83  }