How to use RunContainer method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.RunContainer

suite.go

Source:suite.go Github

copy

Full Screen

...52 })53 return suite54}55type ContainerRequest = testcontainers.ContainerRequest56// RunContainer runs a container, capturing its logs as artifacts, and stopping57// the container when the test finishes.58func (s *Suite) RunContainer(t *testing.T, name string, captureLogs bool, req ContainerRequest) *Container {59 t.Helper()60 ctx := s.Context(t)61 req.Name = fmt.Sprintf("%s-%s", s.Name, name)62 req.AutoRemove = false63 req.SkipReaper = s.opts.DisableReaper64 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{65 ContainerRequest: req,66 Started: true,67 })68 require.NoError(t, err)69 logs := &logConsumer{}70 container.FollowOutput(logs)71 require.NoError(t, container.StartLogProducer(ctx))72 t.Cleanup(func() {73 if err := container.StopLogProducer(); err != nil {74 t.Logf("failed to stop log producer: %v\n", err)75 }76 if captureLogs {77 s.CaptureArtifact(78 fmt.Sprintf("%s.log", name),79 logs.bytes(),80 )81 }82 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)83 defer cancel()84 state, err := container.State(ctx)85 if err != nil {86 t.Logf("failed to get container state (%s): %v\n", req.Name, err)87 return88 }89 if !state.Running {90 return91 }92 if err := container.Terminate(ctx); err != nil {93 t.Logf("failed to terminate container (%s): %v\n", req.Name, err)94 }95 })96 hostIP, err := container.Host(ctx)97 require.NoError(t, err)98 containerIP, err := container.ContainerIP(ctx)99 require.NoError(t, err)100 hostMappedPorts := make(map[nat.Port]int, len(req.ExposedPorts))101 for _, portString := range req.ExposedPorts {102 port := nat.Port(portString)103 hostPort, err := container.MappedPort(ctx, port)104 require.NoError(t, err)105 hostMappedPorts[port] = hostPort.Int()106 }107 return &Container{108 Name: req.Name,109 Container: container,110 HostIP: hostIP,111 ContainerIP: containerIP,112 MappedPorts: hostMappedPorts,113 }114}115// Context returns a context that will be canceled when the test finishes.116func (s *Suite) Context(t *testing.T) context.Context {117 ctx, cancel := context.WithCancel(context.Background())118 t.Cleanup(cancel)119 return ctx120}121// CaptureArtifact stores the given data to be written to disk when the test122// finishes.123func (s *Suite) CaptureArtifact(name string, data []byte) {124 s.mu.Lock()125 defer s.mu.Unlock()126 s.artifacts[name] = data127}128func (s *Suite) cleanup(t *testing.T) {129 s.mu.Lock()130 defer s.mu.Unlock()131 if s.opts.OutputDir == "" {132 return133 }134 for name, data := range s.artifacts {135 if err := os.WriteFile(filepath.Join(s.opts.OutputDir, name), data, 0660); err != nil {136 t.Logf("failed to write artifact %s: %v", name, err)137 }138 }139}140// Volume returns a Docker volume that can be used to share files between141// containers. You can also add files from the host using WriteFile. The142// volume will be deleted when the test finishes.143func (s *Suite) Volume(t *testing.T) *Volume {144 t.Helper()145 s.mu.Lock()146 defer s.mu.Unlock()147 if s.volume == nil {148 docker, _, _, err := testcontainers.NewDockerClient()149 require.NoError(t, err)150 v, err := docker.VolumeCreate(151 s.Context(t),152 volume.VolumeCreateBody{153 Name: fmt.Sprintf("%s-volume", s.Name),154 },155 )156 require.NoError(t, err)157 t.Cleanup(func() {158 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)159 defer cancel()160 if err := docker.VolumeRemove(ctx, v.Name, true); err != nil {161 t.Logf("failed to remove volume: %v", err)162 }163 })164 s.volume = &Volume{Volume: v, suite: s}165 }166 return s.volume167}168type Container struct {169 testcontainers.Container170 Name string171 HostIP string172 ContainerIP string173 MappedPorts map[nat.Port]int174}175// Network returns the container's network that can be used to join other176// containers to it.177func (c *Container) Network() container.NetworkMode {178 return container.NetworkMode(fmt.Sprintf("container:%s", c.Name))179}180type Volume struct {181 types.Volume182 suite *Suite183 mu sync.Mutex184 container *Container185}186// WriteFile adds a file to the Volume using a "pause" container.187func (v *Volume) WriteFile(t *testing.T, name string, contents []byte) {188 v.mu.Lock()189 defer v.mu.Unlock()190 const mountPoint = "/data"191 if v.container == nil {192 v.container = v.suite.RunContainer(t, "volume", false, ContainerRequest{193 Image: pauseContainerImage,194 Mounts: []testcontainers.ContainerMount{195 testcontainers.VolumeMount(v.Name, mountPoint),196 },197 })198 }199 ctx := v.suite.Context(t)200 err := v.container.CopyToContainer(ctx, contents, filepath.Join(mountPoint, name), 0444)201 require.NoError(t, err)202}203type logConsumer struct {204 mu sync.Mutex205 buf bytes.Buffer206}...

Full Screen

Full Screen

secret_test.go

Source:secret_test.go Github

copy

Full Screen

...11)12func initSecretService(f influxdbtesting.SecretServiceFields, t *testing.T) (influxdb.SecretService, func()) {13 token := "test"14 ctx := context.Background()15 vaultC, err := testcontainer.RunContainer(ctx, "vault", testcontainer.RequestContainer{16 ExportedPort: []string{17 "8200/tcp",18 },19 Cmd: fmt.Sprintf(`vault server -dev -dev-listen-address 0.0.0.0:8200 -dev-root-token-id=%s`, token),20 })21 if err != nil {22 t.Fatalf("failed to initialize vault testcontiner: %v", err)23 }24 ip, port, err := vaultC.GetHostEndpoint(ctx, "8200/tcp")25 if err != nil {26 t.Fatal(err)27 }28 s, err := vault.NewSecretService()29 if err != nil {...

Full Screen

Full Screen

tls.go

Source:tls.go Github

copy

Full Screen

...10func GenerateServerTLS(t *testing.T, suite *Suite) {11 t.Helper()12 ctx := suite.Context(t)13 volume := suite.Volume(t)14 container := suite.RunContainer(t, "generate-tls-certs", false, ContainerRequest{15 Image: suite.opts.ServerImage,16 Cmd: []string{"sleep", "infinity"},17 Mounts: []testcontainers.ContainerMount{18 testcontainers.VolumeMount(volume.Name, "/data"),19 },20 })21 cmds := []string{22 "consul tls ca create",23 "cp consul-agent-ca.pem /data/ca-cert.pem",24 "consul tls cert create -server",25 "cp dc1-server-consul-0.pem /data/server-cert.pem",26 "cp dc1-server-consul-0-key.pem /data/server-key.pem",27 "chmod 444 /data/server-key.pem",28 }...

Full Screen

Full Screen

RunContainer

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.ForListeningPort("80/tcp"),7 }8 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 p, err := c.MappedPort(ctx, "80")14 if err != nil {15 log.Fatal(err)16 }17 ip, err := c.Host(ctx)18 if err != nil {19 log.Fatal(err)20 }21 time.Sleep(5 * time.Second)22}

Full Screen

Full Screen

RunContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"5432/tcp"},6 WaitingFor: wait.ForLog("database system is ready to accept connections"),7 }8 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer postgresContainer.Terminate(ctx)14 ip, err := postgresContainer.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := postgresContainer.MappedPort(ctx, "5432")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Printf("Postgres is available at %s:%s23", ip, port.Port())24 time.Sleep(30 * time.Second)25}

Full Screen

Full Screen

RunContainer

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.ForLog("Serving HTTP on

Full Screen

Full Screen

RunContainer

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.ForLog("Ready to accept connections"),7 }8 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatalf("Could not start container: %s", err)12 }13 redisContainer.GetContainerName()14 redisHost, _ := redisContainer.Host(ctx)15 redisPort, _ := redisContainer.MappedPort(ctx, "6379")16 fmt.Println("REDIS HOST: ", redisHost)17 fmt.Println("REDIS PORT: ", redisPort.Int())18 redisContainer2, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{19 })20 if err != nil {21 log.Fatalf("Could not start container: %s", err)22 }23 redisHost2, _ := redisContainer2.Host(ctx)24 redisPort2, _ := redisContainer2.MappedPort(ctx, "6379")25 fmt.Println("REDIS HOST: ", redisHost2)26 fmt.Println("REDIS PORT: ", redisPort2.Int())27 redisContainer3, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{28 })29 if err != nil {30 log.Fatalf("Could not start container: %s", err)31 }32 redisHost3, _ := redisContainer3.Host(ctx)33 redisPort3, _ := redisContainer3.MappedPort(ctx, "6379")34 fmt.Println("REDIS HOST: ", redisHost3)35 fmt.Println("REDIS

Full Screen

Full Screen

RunContainer

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.ForLog("Welcome to nginx!"),7 }8 nginxContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 req1 := testcontainers.ContainerRequest{14 ExposedPorts: []string{"80/tcp"},15 WaitingFor: wait.ForLog("AH00558: apache2: Could not reliably determine the server's fully qualified domain name"),16 }17 phpContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{18 })19 if err != nil {20 panic(err)21 }22 port, err := nginxContainer.MappedPort(ctx, "80")23 if err != nil {24 panic(err)25 }26 req2 := testcontainers.ContainerRequest{27 ExposedPorts: []string{"3306/tcp"},28 Env: map[string]string{"MYSQL_ROOT_PASSWORD": "root"},29 WaitingFor: wait.ForLog("

Full Screen

Full Screen

RunContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())5 if err != nil {6 panic(err)7 }8 _, err = cli.Ping(ctx)9 if err != nil {10 panic(err)11 }12 config := &container.Config{13 Cmd: []string{"sh", "-c", "go run /go/src/github.com/testcontainers/testcontainers-go/examples/gotest/main.go"},14 Env: []string{15 },16 }17 hostConfig := &container.HostConfig{18 Mounts: []mount.Mount{19 {20 },21 },22 }23 resp, err := cli.ContainerCreate(ctx, config, hostConfig, nil, "testcontainer")24 if err != nil {25 panic(err)26 }27 if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {28 panic(err)29 }30 ip, err := getContainerIP(ctx, cli, resp.ID)31 if err != nil {32 panic(err)33 }34 _, err = cli.ContainerWait(ctx, resp.ID)35 if err != nil {36 panic(err)

Full Screen

Full Screen

RunContainer

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 WaitingFor: wait.ForLog("hello world"),7 }8 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer container.Terminate(ctx)14 out, err := container.Exec(ctx, []string{"echo", "hello world"})15 if err != nil {16 panic(err)17 }18 fmt.Println(out)19}

Full Screen

Full Screen

RunContainer

Using AI Code Generation

copy

Full Screen

1containerID, err := testcontainers.RunContainer("hello-world", "hello-world", "80")2if err != nil {3 fmt.Println(err)4}5err = testcontainers.StopContainer(containerID)6if err != nil {7 fmt.Println(err)8}9err = testcontainers.DeleteContainer(containerID)10if err != nil {11 fmt.Println(err)12}13containerID, err = testcontainers.RunContainer("hello-world", "hello-world", "80")14if err != nil {15 fmt.Println(err)16}17err = testcontainers.DeleteContainer(containerID)18if err != nil {19 fmt.Println(err)20}

Full Screen

Full Screen

RunContainer

Using AI Code Generation

copy

Full Screen

1import (2type TestContainers struct {3}4func (t *TestContainers) RunContainer() {5 ctx := context.Background()6 req := testcontainers.ContainerRequest{7 ExposedPorts: []string{"8080/tcp"},8 WaitingFor: wait.ForLog("Started Application in"),9 }10 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{11 })12 if err != nil {13 log.Fatalf("Could not start container: %v", err)14 }15 ip, err := container.Host(ctx)16 if err != nil {17 log.Fatalf("Could not get container IP: %v", err)18 }19 mappedPort, err := container.MappedPort(ctx, "8080")20 if err != nil {21 log.Fatalf("Could not get container port: %v", err)22 }23 t.Port = mappedPort.Port()24}25func (t *TestContainers) StopContainer() {26 err := t.Container.Terminate(context.Background())27 if err != nil {28 log.Fatalf("Could not stop container: %v", err)29 }30}31func (t *TestContainers) GetHost() string {32}33func (t *TestContainers) GetPort() string {34}35import (36func TestContainer(t *testing.T) {37 testContainer := TestContainers{Image: "testcontainers/ryuk

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