github.com/pwn-term/docker@v0.0.0-20210616085119-6e977cce2565/cli/e2e/container/kill_test.go (about)

     1  package container
     2  
     3  import (
     4  	"strings"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/docker/cli/e2e/internal/fixtures"
     9  	"gotest.tools/v3/icmd"
    10  	"gotest.tools/v3/poll"
    11  )
    12  
    13  func TestKillContainer(t *testing.T) {
    14  	containerID := runBackgroundTop(t)
    15  
    16  	// Kill with SIGTERM should kill the process
    17  	result := icmd.RunCmd(
    18  		icmd.Command("docker", "kill", "-s", "SIGTERM", containerID),
    19  	)
    20  
    21  	result.Assert(t, icmd.Success)
    22  	poll.WaitOn(t, containerStatus(t, containerID, "exited"), poll.WithDelay(100*time.Millisecond), poll.WithTimeout(5*time.Second))
    23  
    24  	// Kill on a stop container should return an error
    25  	result = icmd.RunCmd(
    26  		icmd.Command("docker", "kill", containerID),
    27  	)
    28  	result.Assert(t, icmd.Expected{
    29  		ExitCode: 1,
    30  		Err:      "is not running",
    31  	})
    32  }
    33  
    34  func runBackgroundTop(t *testing.T) string {
    35  	result := icmd.RunCommand("docker", "run", "-d", fixtures.AlpineImage, "top")
    36  	result.Assert(t, icmd.Success)
    37  	return strings.TrimSpace(result.Stdout())
    38  }
    39  
    40  func containerStatus(t *testing.T, containerID, status string) func(poll.LogT) poll.Result {
    41  	return func(poll.LogT) poll.Result {
    42  		result := icmd.RunCommand("docker", "inspect", "-f", "{{ .State.Status }}", containerID)
    43  		result.Assert(t, icmd.Success)
    44  		actual := strings.TrimSpace(result.Stdout())
    45  		if actual == status {
    46  			return poll.Success()
    47  		}
    48  		return poll.Continue("expected status %s != %s", status, actual)
    49  	}
    50  }