Best Testcontainers-go code snippet using testcontainers.executeCompose
compose_local.go
Source:compose_local.go
...66 f(opts)67}68// Down executes docker-compose down69func (dc *LocalDockerCompose) Down() ExecError {70 return executeCompose(dc, []string{"down", "--remove-orphans", "--volumes"})71}72func (dc *LocalDockerCompose) getDockerComposeEnvironment() map[string]string {73 environment := map[string]string{}74 composeFileEnvVariableValue := ""75 for _, abs := range dc.absComposeFilePaths {76 composeFileEnvVariableValue += abs + string(os.PathListSeparator)77 }78 environment[envProjectName] = dc.Identifier79 environment[envComposeFile] = composeFileEnvVariableValue80 return environment81}82func (dc *LocalDockerCompose) containerNameFromServiceName(service, separator string) string {83 return dc.Identifier + separator + service84}85func (dc *LocalDockerCompose) applyStrategyToRunningContainer() error {86 cli, err := client.NewClientWithOpts(client.FromEnv)87 if err != nil {88 return err89 }90 cli.NegotiateAPIVersion(context.Background())91 for k := range dc.WaitStrategyMap {92 containerName := dc.containerNameFromServiceName(k.service, "_")93 composeV2ContainerName := dc.containerNameFromServiceName(k.service, "-")94 f := filters.NewArgs(95 filters.Arg("name", containerName),96 filters.Arg("name", composeV2ContainerName),97 filters.Arg("name", k.service))98 containerListOptions := types.ContainerListOptions{Filters: f, All: true}99 containers, err := cli.ContainerList(context.Background(), containerListOptions)100 if err != nil {101 return fmt.Errorf("error %w occured while filtering the service %s: %d by name and published port", err, k.service, k.publishedPort)102 }103 if len(containers) == 0 {104 return fmt.Errorf("service with name %s not found in list of running containers", k.service)105 }106 // The length should always be a list of 1, since we are matching one service name at a time107 if l := len(containers); l > 1 {108 return fmt.Errorf("expecting only one running container for %s but got %d", k.service, l)109 }110 container := containers[0]111 strategy := dc.WaitStrategyMap[k]112 dockerProvider, err := NewDockerProvider(WithLogger(dc.Logger))113 if err != nil {114 return fmt.Errorf("unable to create new Docker Provider: %w", err)115 }116 dockercontainer := &DockerContainer{ID: container.ID, WaitingFor: strategy, provider: dockerProvider, logger: dc.Logger}117 err = strategy.WaitUntilReady(context.Background(), dockercontainer)118 if err != nil {119 return fmt.Errorf("Unable to apply wait strategy %v to service %s due to %w", strategy, k.service, err)120 }121 }122 return nil123}124// Invoke invokes the docker compose125func (dc *LocalDockerCompose) Invoke() ExecError {126 return executeCompose(dc, dc.Cmd)127}128// WaitForService sets the strategy for the service that is to be waited on129func (dc *LocalDockerCompose) WaitForService(service string, strategy wait.Strategy) DockerCompose {130 dc.waitStrategySupplied = true131 dc.WaitStrategyMap[waitService{service: service}] = strategy132 return dc133}134// WithCommand assigns the command135func (dc *LocalDockerCompose) WithCommand(cmd []string) DockerCompose {136 dc.Cmd = cmd137 return dc138}139// WithEnv assigns the environment140func (dc *LocalDockerCompose) WithEnv(env map[string]string) DockerCompose {141 dc.Env = env142 return dc143}144// WithExposedService sets the strategy for the service that is to be waited on. If multiple strategies145// are given for a single service running on different ports, both strategies will be applied on the same container146func (dc *LocalDockerCompose) WithExposedService(service string, port int, strategy wait.Strategy) DockerCompose {147 dc.waitStrategySupplied = true148 dc.WaitStrategyMap[waitService{service: service, publishedPort: port}] = strategy149 return dc150}151// determineVersion checks which version of docker-compose is installed152// depending on the version services names are composed in a different way153func (dc *LocalDockerCompose) determineVersion() error {154 execErr := executeCompose(dc, []string{"version", "--short"})155 if err := execErr.Error; err != nil {156 return err157 }158 components := bytes.Split(execErr.StdoutOutput, []byte("."))159 if componentsLen := len(components); componentsLen != 3 {160 return fmt.Errorf("expected 3 version components in %s", execErr.StdoutOutput)161 }162 majorVersion, err := strconv.ParseInt(string(components[0]), 10, 8)163 if err != nil {164 return err165 }166 switch majorVersion {167 case 1:168 dc.ComposeVersion = composeVersion1{}169 case 2:170 dc.ComposeVersion = composeVersion2{}171 default:172 return fmt.Errorf("unexpected compose version %d", majorVersion)173 }174 return nil175}176// validate checks if the files to be run in the compose are valid YAML files, setting up177// references to all services in them178func (dc *LocalDockerCompose) validate() error {179 type compose struct {180 Services map[string]interface{}181 }182 for _, abs := range dc.absComposeFilePaths {183 c := compose{}184 yamlFile, err := ioutil.ReadFile(abs)185 if err != nil {186 return err187 }188 err = yaml.Unmarshal(yamlFile, &c)189 if err != nil {190 return err191 }192 if dc.Services == nil {193 dc.Services = c.Services194 } else {195 for k, v := range c.Services {196 dc.Services[k] = v197 }198 }199 }200 return nil201}202// ExecError is super struct that holds any information about an execution error, so the client code203// can handle the result204type ExecError struct {205 Command []string206 StdoutOutput []byte207 StderrOutput []byte208 Error error209 Stdout error210 Stderr error211}212// execute executes a program with arguments and environment variables inside a specific directory213func execute(214 dirContext string, environment map[string]string, binary string, args []string) ExecError {215 var errStdout, errStderr error216 cmd := exec.Command(binary, args...)217 cmd.Dir = dirContext218 cmd.Env = os.Environ()219 for key, value := range environment {220 cmd.Env = append(cmd.Env, key+"="+value)221 }222 stdoutIn, _ := cmd.StdoutPipe()223 stderrIn, _ := cmd.StderrPipe()224 stdout := newCapturingPassThroughWriter(os.Stdout)225 stderr := newCapturingPassThroughWriter(os.Stderr)226 err := cmd.Start()227 if err != nil {228 execCmd := []string{"Starting command", dirContext, binary}229 execCmd = append(execCmd, args...)230 return ExecError{231 // add information about the CMD and arguments used232 Command: execCmd,233 StdoutOutput: stdout.Bytes(),234 StderrOutput: stderr.Bytes(),235 Error: err,236 Stderr: errStderr,237 Stdout: errStdout,238 }239 }240 var wg sync.WaitGroup241 wg.Add(1)242 go func() {243 _, errStdout = io.Copy(stdout, stdoutIn)244 wg.Done()245 }()246 _, errStderr = io.Copy(stderr, stderrIn)247 wg.Wait()248 err = cmd.Wait()249 execCmd := []string{"Reading std", dirContext, binary}250 execCmd = append(execCmd, args...)251 return ExecError{252 Command: execCmd,253 StdoutOutput: stdout.Bytes(),254 StderrOutput: stderr.Bytes(),255 Error: err,256 Stderr: errStderr,257 Stdout: errStdout,258 }259}260func executeCompose(dc *LocalDockerCompose, args []string) ExecError {261 if which(dc.Executable) != nil {262 return ExecError{263 Command: []string{dc.Executable},264 Error: fmt.Errorf("Local Docker Compose not found. Is %s on the PATH?", dc.Executable),265 }266 }267 environment := dc.getDockerComposeEnvironment()268 for k, v := range dc.Env {269 environment[k] = v270 }271 var cmds []string272 pwd := "."273 if len(dc.absComposeFilePaths) > 0 {274 pwd, _ = filepath.Split(dc.absComposeFilePaths[0])...
compose.go
Source:compose.go
...55 if len(scaleCmds) > 0 {56 cmds = append(cmds, "--scale")57 cmds = append(cmds, scaleCmds...)58 }59 err := executeCompose(ctx, profile, services, cmds, persistedEnv)60 if err != nil {61 return err62 }63 return nil64}65// ExecCommandInService executes a command in a service from a profile66func (sm *DockerServiceManager) ExecCommandInService(ctx context.Context, profile ServiceRequest, image ServiceRequest, serviceName string, cmds []string, env map[string]string, detach bool) error {67 services := []ServiceRequest{68 image, // image for the service69 }70 composeArgs := []string{"exec", "-T"}71 if detach {72 composeArgs = append(composeArgs, "-d")73 }74 composeArgs = append(composeArgs, "--index", fmt.Sprintf("%d", image.Scale))75 composeArgs = append(composeArgs, serviceName)76 composeArgs = append(composeArgs, cmds...)77 err := sm.RunCommand(ctx, profile, services, composeArgs, env)78 if err != nil {79 log.WithFields(log.Fields{80 "command": cmds,81 "error": err,82 "service": serviceName,83 }).Error("Could not execute command in service container")84 return err85 }86 return nil87}88// RemoveServicesFromCompose removes services from a running docker compose89func (sm *DockerServiceManager) RemoveServicesFromCompose(ctx context.Context, profile ServiceRequest, services []ServiceRequest, env map[string]string) error {90 span, _ := apm.StartSpanOptions(ctx, "Remove services from Docker Compose", "docker-compose.services.remove", apm.SpanOptions{91 Parent: apm.SpanFromContext(ctx).TraceContext(),92 })93 span.Context.SetLabel("profile", profile)94 span.Context.SetLabel("services", services)95 defer span.End()96 log.WithFields(log.Fields{97 "profile": profile,98 "services": services,99 }).Trace("Removing services from compose")100 run := state.Recover(profile.Name+"-profile", config.OpDir())101 persistedEnv := run.Env102 for k, v := range env {103 persistedEnv[k] = v104 }105 for _, srv := range services {106 command := []string{"rm", "-fvs"}107 command = append(command, srv.Name)108 err := executeCompose(ctx, profile, services, command, persistedEnv)109 if err != nil {110 log.WithFields(log.Fields{111 "command": command,112 "service": srv,113 "profile": profile,114 }).Error("Could not remove service from compose")115 return err116 }117 log.WithFields(log.Fields{118 "profile": profile,119 "service": srv,120 }).Debug("Service removed from compose")121 }122 return nil123}124// RunCommand executes a docker-compose command in a running a docker compose125func (sm *DockerServiceManager) RunCommand(ctx context.Context, profile ServiceRequest, services []ServiceRequest, composeArgs []string, env map[string]string) error {126 return executeCompose(ctx, profile, services, composeArgs, env)127}128// RunCompose runs a docker compose by its name129func (sm *DockerServiceManager) RunCompose(ctx context.Context, profile ServiceRequest, services []ServiceRequest, env map[string]string) error {130 span, _ := apm.StartSpanOptions(ctx, "Starting Docker Compose files", "docker-compose.services.up", apm.SpanOptions{131 Parent: apm.SpanFromContext(ctx).TraceContext(),132 })133 span.Context.SetLabel("services", services)134 defer span.End()135 return executeCompose(ctx, profile, services, []string{"up", "-d"}, env)136}137// StopCompose stops a docker compose by profile name, including all orphan services138func (sm *DockerServiceManager) StopCompose(ctx context.Context, profile ServiceRequest) error {139 span, _ := apm.StartSpanOptions(ctx, "Stopping Docker Compose profile", "docker-compose.services.down", apm.SpanOptions{140 Parent: apm.SpanFromContext(ctx).TraceContext(),141 })142 span.Context.SetLabel("profile", profile)143 defer span.End()144 ID := profile.Name + "-profile"145 run := state.Recover(ID, config.OpDir())146 persistedEnv := run.Env147 err := executeCompose(ctx, profile, []ServiceRequest{}, []string{"down", "--remove-orphans"}, persistedEnv)148 if err != nil {149 return fmt.Errorf("could not stop compose file: %v - %v", profile, err)150 }151 defer state.Destroy(ID, config.OpDir())152 log.WithFields(log.Fields{153 "profile": profile.Name,154 }).Trace("Docker compose down.")155 return nil156}157func executeCompose(ctx context.Context, profile ServiceRequest, services []ServiceRequest, command []string, env map[string]string) error {158 span, _ := apm.StartSpanOptions(ctx, "Executing Docker Compose command", "docker-compose.services.exec", apm.SpanOptions{159 Parent: apm.SpanFromContext(ctx).TraceContext(),160 })161 span.Context.SetLabel("profile", profile)162 span.Context.SetLabel("services", services)163 span.Context.SetLabel("command", command)164 defer span.End()165 profileComposeFilePath, err := getComposeFile(true, profile.GetName())166 if err != nil {167 return fmt.Errorf("could not get compose file for profile: %s - %v", profileComposeFilePath, err)168 }169 composeFilePaths := []string{profileComposeFilePath}170 for _, srv := range services {171 composeFilePath, err := getComposeFile(false, srv.GetName())...
executeCompose
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"9200/tcp", "9300/tcp"},6 WaitingFor: wait.ForLog("started"),7 }8 esContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer esContainer.Terminate(ctx)14 ip, err := esContainer.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := esContainer.MappedPort(ctx, "9200")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println(ip, port.Int())23 time.Sleep(5 * time.Second)24 if err != nil {25 log.Fatal(err)26 }27 defer resp.Body.Close()28}
executeCompose
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 compose := testcontainers.NewLocalDockerCompose([]string{"docker-compose.yml"}, "myproject")5 compose.WithCommand([]string{"up", "-d"})6 compose.WithEnv(map[string]string{"COMPOSE_PROJECT_NAME": "myproject"})7 compose.WithCommand([]string{"up", "-d"})8 err := compose.Execute(ctx, func(ctx context.Context) error {9 })10 if err != nil {11 panic(err)12 }13}14import (15func main() {16 ctx := context.Background()17 compose := testcontainers.NewLocalDockerCompose([]string{"docker-compose.yml"}, "myproject")18 compose.WithCommand([]string{"up", "-d"})19 compose.WithEnv(map[string]string{"COMPOSE_PROJECT_NAME": "myproject"})20 compose.WithCommand([]string{"up", "-d"})21 err := compose.Execute(ctx, func(ctx context.Context) error {22 })23 if err != nil {24 panic(err)25 }26}27import (28func main() {29 ctx := context.Background()30 compose := testcontainers.NewLocalDockerCompose([]string{"docker-compose.yml"}, "myproject")31 compose.WithCommand([]string{"up", "-d"})32 compose.WithEnv(map[string]string{"COMPOSE_PROJECT_NAME": "myproject"})33 compose.WithCommand([]string{"up", "-d"})34 err := compose.Execute(ctx, func(ctx context.Context) error {35 })36 if err != nil {37 panic(err)38 }39}40import (41func main() {42 ctx := context.Background()
executeCompose
Using AI Code Generation
1import (2func main() {3 ctx := testcontainers.GenericContainerRequest{4 ContainerRequest: testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 WaitingFor: wait.ForHTTP("/"),7 },8 }9 container, err := testcontainers.GenericContainer(ctx)10 if err != nil {11 log.Fatal(err)12 }13 ip, err := container.Host(ctx)14 if err != nil {15 log.Fatal(err)16 }17 port, err := container.MappedPort(ctx, "80")18 if err != nil {19 log.Fatal(err)20 }21 fmt.Println(ip, port.Int())22 err = container.Terminate(ctx)23 if err != nil {24 log.Fatal(err)25 }26}
executeCompose
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 }7 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{8 })9 if err != nil {10 log.Fatal(err)11 }12 ip, err := container.Host(ctx)13 if err != nil {14 log.Fatal(err)15 }16 port, err := container.MappedPort(ctx, "80")17 if err != nil {18 log.Fatal(err)19 }20 id, err := container.ContainerID(ctx)21 if err != nil {22 log.Fatal(err)23 }24 host, err := container.Host(ctx)25 if err != nil {26 log.Fatal(err)27 }28 name, err := container.ContainerName(ctx)29 if err != nil {30 log.Fatal(err)31 }32 network, err := container.Network(ctx)33 if err != nil {34 log.Fatal(err)35 }36 image, err := container.Image(ctx)37 if err != nil {38 log.Fatal(err)39 }40 state, err := container.State(ctx)41 if err != nil {42 log.Fatal(err)43 }44 creationTime, err := container.CreationTime(ctx)45 if err != nil {46 log.Fatal(err)47 }48 internalIp, err := container.InternalIP(ctx)49 if err != nil {50 log.Fatal(err)51 }52 labels, err := container.Labels(ctx)53 if err != nil {54 log.Fatal(err)55 }56 env, err := container.Env(ctx)57 if err != nil {58 log.Fatal(err)59 }60 logs, err := container.Logs(ctx)61 if err != nil {62 log.Fatal(err)63 }64 waitStrategy, err := container.WaitStrategy(ctx)
executeCompose
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 compose := testcontainers.NewLocalDockerCompose([]string{"./docker-compose.yml"}, "test")5 _, err := compose.WithCommand([]string{"up", "-d"}).Invoke()6 if err != nil {7 panic(err)8 }9 defer compose.Down(ctx)10 _, err = compose.Exec(ctx, "app", []string{"echo", "test"})11 if err != nil {12 panic(err)13 }14 ip, err := compose.Exec(ctx, "app", []string{"sh", "-c", "echo $APP_IP"})15 if err != nil {16 panic(err)17 }18 fmt.Println(ip)19 out, err := compose.Exec(ctx, "app", []string{"cat", "/tmp/test"})20 if err != nil {21 panic(err)22 }23 f, err := os.Create("test")24 if err != nil {25 panic(err)26 }27 defer f.Close()28 _, err = io.Copy(f, out)29 if err != nil {30 panic(err)31 }32 _, err = compose.Exec(ctx, "app", []string{"echo", "test"})33 if err != nil {34 panic(err)35 }36 logs, err := compose.Logs(ctx)37 if err != nil {38 panic(err)39 }40 fmt.Println(logs)41}
executeCompose
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 composeFile, err := filepath.Abs("./docker-compose.yaml")5 if err != nil {6 log.Fatal(err)7 }8 containers, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 ContainerRequest: testcontainers.ContainerRequest{10 ExposedPorts: []string{"8080/tcp"},11 WaitingFor: wait.ForHTTP("/"),12 },13 })14 if err != nil {15 log.Fatal(err)16 }17 defer containers.Terminate(ctx)18 ip, err := containers.Host(ctx)19 if err != nil {20 log.Fatal(err)21 }22 port, err := containers.MappedPort(ctx, "8080")23 if err != nil {24 log.Fatal(err)25 }26 fmt.Println(url)27 cmd := exec.Command("docker-compose", "-f", composeFile, "up", "-d")28 if err := cmd.Run(); err != nil {29 log.Fatal(err)30 }31 time.Sleep(10 * time.Second)32 cmd = exec.Command("docker-compose", "-f", composeFile, "down")33 if err := cmd.Run(); err != nil {34 log.Fatal(err)35 }36}
executeCompose
Using AI Code Generation
1import (2func TestMain(m *testing.M) {3 os.Exit(m.Run())4}5func TestCompose(t *testing.T) {6 ctx := context.Background()7 compose := testcontainers.NewLocalDockerCompose([]string{"docker-compose.yml"}, "test")8 Invoke(ctx)9 if err != nil {10 panic(err)11 }12 defer func() {13 Invoke(ctx)14 if err != nil {15 panic(err)16 }17 }()18 time.Sleep(10 * time.Second)19 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{20 ContainerRequest: testcontainers.ContainerRequest{21 ExposedPorts: []string{"6379/tcp"},22 WaitingFor: wait.ForListeningPort("6379/tcp"),23 },24 })25 if err != nil {26 panic(err)27 }28 defer container.Terminate(ctx)29 host, err := container.Host(ctx)30 if err != nil {31 panic(err)32 }33 port, err := container.MappedPort(ctx, "6379/tcp")34 if err != nil {35 panic(err)36 }37 _, err = redis.Dial("tcp", fmt.Sprintf("%s:%s", host, port.Port()))38 if err != nil {39 panic(err)40 }41}42func TestComposeWithLogs(t *testing.T) {43 ctx := context.Background()44 compose := testcontainers.NewLocalDockerCompose([]string{"docker-compose.yml"}, "test")45 Invoke(ctx)46 if err != nil {47 panic(err)48 }49 defer func() {50 Invoke(ctx)51 if err != nil {52 panic(err)53 }54 }()
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!