github.com/darmach/terratest@v0.34.8-0.20210517103231-80931f95e3ff/modules/docker/stop.go (about)

     1  package docker
     2  
     3  import (
     4  	"strconv"
     5  
     6  	"github.com/gruntwork-io/terratest/modules/logger"
     7  	"github.com/gruntwork-io/terratest/modules/shell"
     8  	"github.com/gruntwork-io/terratest/modules/testing"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  // StopOptions defines the options that can be passed to the 'docker stop' command
    13  type StopOptions struct {
    14  	// Seconds to wait for stop before killing the container (default 10)
    15  	Time int
    16  
    17  	// Set a logger that should be used. See the logger package for more info.
    18  	Logger *logger.Logger
    19  }
    20  
    21  // Stop runs the 'docker stop' command for the given containers and return the stdout/stderr. This method fails
    22  // the test if there are any errors
    23  func Stop(t testing.TestingT, containers []string, options *StopOptions) string {
    24  	out, err := StopE(t, containers, options)
    25  	require.NoError(t, err)
    26  	return out
    27  }
    28  
    29  // StopE runs the 'docker stop' command for the given containers and returns any errors.
    30  func StopE(t testing.TestingT, containers []string, options *StopOptions) (string, error) {
    31  	options.Logger.Logf(t, "Running 'docker stop' on containers '%s'", containers)
    32  
    33  	args, err := formatDockerStopArgs(containers, options)
    34  	if err != nil {
    35  		return "", err
    36  	}
    37  
    38  	cmd := shell.Command{
    39  		Command: "docker",
    40  		Args:    args,
    41  		Logger:  options.Logger,
    42  	}
    43  
    44  	return shell.RunCommandAndGetOutputE(t, cmd)
    45  
    46  }
    47  
    48  // formatDockerStopArgs formats the arguments for the 'docker stop' command
    49  func formatDockerStopArgs(containers []string, options *StopOptions) ([]string, error) {
    50  	args := []string{"stop"}
    51  
    52  	if options.Time != 0 {
    53  		args = append(args, "--time", strconv.Itoa(options.Time))
    54  	}
    55  
    56  	args = append(args, containers...)
    57  
    58  	return args, nil
    59  }