How to use applyStrategyToRunningContainer method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.applyStrategyToRunningContainer

compose.go

Source:compose.go Github

copy

Full Screen

...112}113func (dc *LocalDockerCompose) containerNameFromServiceName(service, separator string) string {114 return dc.Identifier + separator + service115}116func (dc *LocalDockerCompose) applyStrategyToRunningContainer() error {117 cli, err := client.NewClientWithOpts(client.FromEnv)118 if err != nil {119 return err120 }121 cli.NegotiateAPIVersion(context.Background())122 for k := range dc.WaitStrategyMap {123 containerName := dc.containerNameFromServiceName(k.service, "_")124 composeV2ContainerName := dc.containerNameFromServiceName(k.service, "-")125 f := filters.NewArgs(126 filters.Arg("name", containerName),127 filters.Arg("name", composeV2ContainerName),128 filters.Arg("name", k.service))129 containerListOptions := types.ContainerListOptions{Filters: f}130 containers, err := cli.ContainerList(context.Background(), containerListOptions)131 if err != nil {132 return fmt.Errorf("error %w occured while filtering the service %s: %d by name and published port", err, k.service, k.publishedPort)133 }134 if len(containers) == 0 {135 return fmt.Errorf("service with name %s not found in list of running containers", k.service)136 }137 // The length should always be a list of 1, since we are matching one service name at a time138 if l := len(containers); l > 1 {139 return fmt.Errorf("expecting only one running container for %s but got %d", k.service, l)140 }141 container := containers[0]142 strategy := dc.WaitStrategyMap[k]143 dockerProvider, err := NewDockerProvider(WithLogger(dc.Logger))144 if err != nil {145 return fmt.Errorf("unable to create new Docker Provider: %w", err)146 }147 dockercontainer := &DockerContainer{ID: container.ID, WaitingFor: strategy, provider: dockerProvider, logger: dc.Logger}148 err = strategy.WaitUntilReady(context.Background(), dockercontainer)149 if err != nil {150 return fmt.Errorf("Unable to apply wait strategy %v to service %s due to %w", strategy, k.service, err)151 }152 }153 return nil154}155// Invoke invokes the docker compose156func (dc *LocalDockerCompose) Invoke() ExecError {157 return executeCompose(dc, dc.Cmd)158}159// WaitForService sets the strategy for the service that is to be waited on160func (dc *LocalDockerCompose) WaitForService(service string, strategy wait.Strategy) DockerCompose {161 dc.waitStrategySupplied = true162 dc.WaitStrategyMap[waitService{service: service}] = strategy163 return dc164}165// WithCommand assigns the command166func (dc *LocalDockerCompose) WithCommand(cmd []string) DockerCompose {167 dc.Cmd = cmd168 return dc169}170// WithEnv assigns the environment171func (dc *LocalDockerCompose) WithEnv(env map[string]string) DockerCompose {172 dc.Env = env173 return dc174}175// WithExposedService sets the strategy for the service that is to be waited on. If multiple strategies176// are given for a single service running on different ports, both strategies will be applied on the same container177func (dc *LocalDockerCompose) WithExposedService(service string, port int, strategy wait.Strategy) DockerCompose {178 dc.waitStrategySupplied = true179 dc.WaitStrategyMap[waitService{service: service, publishedPort: port}] = strategy180 return dc181}182// validate checks if the files to be run in the compose are valid YAML files, setting up183// references to all services in them184func (dc *LocalDockerCompose) validate() error {185 type compose struct {186 Services map[string]interface{}187 }188 for _, abs := range dc.absComposeFilePaths {189 c := compose{}190 yamlFile, err := ioutil.ReadFile(abs)191 if err != nil {192 return err193 }194 err = yaml.Unmarshal(yamlFile, &c)195 if err != nil {196 return err197 }198 if dc.Services == nil {199 dc.Services = c.Services200 } else {201 for k, v := range c.Services {202 dc.Services[k] = v203 }204 }205 }206 return nil207}208// ExecError is super struct that holds any information about an execution error, so the client code209// can handle the result210type ExecError struct {211 Command []string212 StdoutOutput []byte213 StderrOutput []byte214 Error error215 Stdout error216 Stderr error217}218// execute executes a program with arguments and environment variables inside a specific directory219func execute(220 dirContext string, environment map[string]string, binary string, args []string) ExecError {221 var errStdout, errStderr error222 cmd := exec.Command(binary, args...)223 cmd.Dir = dirContext224 cmd.Env = os.Environ()225 for key, value := range environment {226 cmd.Env = append(cmd.Env, key+"="+value)227 }228 stdoutIn, _ := cmd.StdoutPipe()229 stderrIn, _ := cmd.StderrPipe()230 stdout := newCapturingPassThroughWriter(os.Stdout)231 stderr := newCapturingPassThroughWriter(os.Stderr)232 err := cmd.Start()233 if err != nil {234 execCmd := []string{"Starting command", dirContext, binary}235 execCmd = append(execCmd, args...)236 return ExecError{237 // add information about the CMD and arguments used238 Command: execCmd,239 StdoutOutput: stdout.Bytes(),240 StderrOutput: stderr.Bytes(),241 Error: err,242 Stderr: errStderr,243 Stdout: errStdout,244 }245 }246 var wg sync.WaitGroup247 wg.Add(1)248 go func() {249 _, errStdout = io.Copy(stdout, stdoutIn)250 wg.Done()251 }()252 _, errStderr = io.Copy(stderr, stderrIn)253 wg.Wait()254 err = cmd.Wait()255 execCmd := []string{"Reading std", dirContext, binary}256 execCmd = append(execCmd, args...)257 return ExecError{258 Command: execCmd,259 StdoutOutput: stdout.Bytes(),260 StderrOutput: stderr.Bytes(),261 Error: err,262 Stderr: errStderr,263 Stdout: errStdout,264 }265}266func executeCompose(dc *LocalDockerCompose, args []string) ExecError {267 if which(dc.Executable) != nil {268 return ExecError{269 Command: []string{dc.Executable},270 Error: fmt.Errorf("Local Docker Compose not found. Is %s on the PATH?", dc.Executable),271 }272 }273 environment := dc.getDockerComposeEnvironment()274 for k, v := range dc.Env {275 environment[k] = v276 }277 cmds := []string{}278 pwd := "."279 if len(dc.absComposeFilePaths) > 0 {280 pwd, _ = filepath.Split(dc.absComposeFilePaths[0])281 for _, abs := range dc.absComposeFilePaths {282 cmds = append(cmds, "-f", abs)283 }284 } else {285 cmds = append(cmds, "-f", "docker-compose.yml")286 }287 cmds = append(cmds, args...)288 execErr := execute(pwd, environment, dc.Executable, cmds)289 err := execErr.Error290 if err != nil {291 args := strings.Join(dc.Cmd, " ")292 return ExecError{293 Command: []string{dc.Executable},294 Error: fmt.Errorf("Local Docker compose exited abnormally whilst running %s: [%v]. %s", dc.Executable, args, err.Error()),295 }296 }297 if dc.waitStrategySupplied {298 // If the wait strategy has been executed once for all services during startup , disable it so that it is not invoked while tearing down299 dc.waitStrategySupplied = false300 if err := dc.applyStrategyToRunningContainer(); err != nil {301 return ExecError{302 Error: fmt.Errorf("one or more wait strategies could not be applied to the running containers: %w", err),303 }304 }305 }306 return execErr307}308// capturingPassThroughWriter is a writer that remembers309// data written to it and passes it to w310type capturingPassThroughWriter struct {311 buf bytes.Buffer312 w io.Writer313}314// newCapturingPassThroughWriter creates new capturingPassThroughWriter...

Full Screen

Full Screen

compose_local.go

Source:compose_local.go Github

copy

Full Screen

...81}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])275 for _, abs := range dc.absComposeFilePaths {276 cmds = append(cmds, "-f", abs)277 }278 } else {279 cmds = append(cmds, "-f", "docker-compose.yml")280 }281 cmds = append(cmds, args...)282 execErr := execute(pwd, environment, dc.Executable, cmds)283 err := execErr.Error284 if err != nil {285 args := strings.Join(dc.Cmd, " ")286 return ExecError{287 Command: []string{dc.Executable},288 Error: fmt.Errorf("Local Docker compose exited abnormally whilst running %s: [%v]. %s", dc.Executable, args, err.Error()),289 }290 }291 if dc.waitStrategySupplied {292 // If the wait strategy has been executed once for all services during startup , disable it so that it is not invoked while tearing down293 dc.waitStrategySupplied = false294 if err := dc.applyStrategyToRunningContainer(); err != nil {295 return ExecError{296 Error: fmt.Errorf("one or more wait strategies could not be applied to the running containers: %w", err),297 }298 }299 }300 return execErr301}302// capturingPassThroughWriter is a writer that remembers303// data written to it and passes it to w304type capturingPassThroughWriter struct {305 buf bytes.Buffer306 w io.Writer307}308// newCapturingPassThroughWriter creates new capturingPassThroughWriter...

Full Screen

Full Screen

applyStrategyToRunningContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"6379/tcp"},6 WaitingFor: wait.ForListeningPort("6379/tcp"),7 }8 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer redisContainer.Terminate(ctx)14 redisHost, err := redisContainer.Host(ctx)15 if err != nil {16 panic(err)17 }18 redisPort, err := redisContainer.MappedPort(ctx, "6379/tcp")19 if err != nil {20 panic(err)21 }22 fmt.Printf("Redis URL: %s23}24import (25func main() {26 ctx := context.Background()27 req := testcontainers.ContainerRequest{28 ExposedPorts: []string{"6379/tcp"},29 WaitingFor: wait.ForListeningPort("6379/tcp"),30 }31 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{32 })33 if err != nil {34 panic(err)35 }36 defer redisContainer.Terminate(ctx)37 redisHost, err := redisContainer.Host(ctx)38 if err != nil {39 panic(err)40 }41 redisPort, err := redisContainer.MappedPort(ctx, "6379/tcp")42 if err != nil {43 panic(err)44 }45 fmt.Printf("Redis URL: %s46}47import (

Full Screen

Full Screen

applyStrategyToRunningContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 Cmd: []string{"sleep", "1m"},6 ExposedPorts: []string{"80/tcp"},7 WaitingFor: wait.ForLog("Listening on port 80"),8 }9 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {

Full Screen

Full Screen

applyStrategyToRunningContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 Cmd: []string{"echo", "hello world"},6 ExposedPorts: []string{"80/tcp"},7 WaitingFor: wait.ForLog("hello world"),8 }9 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 log.Fatal(err)13 }14 defer c.Terminate(ctx)15 ip, err := c.Host(ctx)16 if err != nil {17 log.Fatal(err)18 }19 port, err := c.MappedPort(ctx, "80")20 if err != nil {21 log.Fatal(err)22 }23 fmt.Printf("Container is running at %s:%s", ip, port.Port())24 time.Sleep(5 * time.Second)25}

Full Screen

Full Screen

applyStrategyToRunningContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"6379/tcp"},6 WaitingFor: wait.ForListeningPort("6379/tcp"),7 }8 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer redis.Terminate(ctx)14 redisID, err := redis.ContainerID(ctx)15 if err != nil {16 log.Fatal(err)17 }18 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())19 if err != nil {20 log.Fatal(err)21 }22 redisInfo, err := cli.ContainerInspect(ctx, redisID)23 if err != nil {24 log.Fatal(err)25 }

Full Screen

Full Screen

applyStrategyToRunningContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 WaitingFor: wait.ForHTTP("/"),7 }8 nginxContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer nginxContainer.Terminate(ctx)

Full Screen

Full Screen

applyStrategyToRunningContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"6379/tcp"},6 WaitingFor: wait.ForListeningPort("6379/tcp"),7 }8 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer redisContainer.Terminate(ctx)14 host, err := redisContainer.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := redisContainer.MappedPort(ctx, "6379/tcp")19 if err != nil {20 panic(err)21 }22 fmt.Printf("Host: %s, Port: %s23", host, port.Port())24 err = redisContainer.Apply(ctx, testcontainers.ContainerExecRequest{25 Cmd: []string{"redis-cli", "set", "foo", "bar"},26 })27 if err != nil {28 panic(err)29 }30 time.Sleep(5 * time.Second)31 err = redisContainer.Apply(ctx, testcontainers.ContainerExecRequest{32 Cmd: []string{"redis-cli", "get", "foo"},33 })34 if err != nil {35 panic(err)36 }37}

Full Screen

Full Screen

applyStrategyToRunningContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"9200/tcp"},6 WaitingFor: wait.ForListeningPort("9200/tcp"),7 }8 elasticContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer elasticContainer.Terminate(ctx)14 mappedPort, err := elasticContainer.MappedPort(ctx, "9200/tcp")15 if err != nil {16 panic(err)17 }18 ipAddress, err := elasticContainer.Host(ctx)19 if err != nil {20 panic(err)21 }22 fmt.Printf("Container mapped port: %s", mappedPort.Port())23 fmt.Printf("Container IP address: %s", ipAddress)24 req2 := testcontainers.ContainerRequest{25 ExposedPorts: []string{"9300/tcp"},26 WaitingFor: wait.ForListeningPort("9300/tcp"),27 }28 elasticContainer2, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{29 })30 if err != nil {31 panic(err)32 }33 defer elasticContainer2.Terminate(ctx)34 mappedPort2, err := elasticContainer2.MappedPort(ctx, "9300/tcp")35 if err != nil {36 panic(err)37 }38 ipAddress2, err := elasticContainer2.Host(ctx)39 if err != nil {40 panic(err)41 }

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testcontainers-go automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful