How to use extractDockerHost method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.extractDockerHost

reaper.go

Source:reaper.go Github

copy

Full Screen

...37 // If reaper already exists re-use it38 if reaper != nil {39 return reaper, nil40 }41 dockerHost := extractDockerHost(ctx)42 // Otherwise create a new one43 reaper = &Reaper{44 Provider: provider,45 SessionID: sessionID,46 }47 listeningPort := nat.Port("8080/tcp")48 req := ContainerRequest{49 Image: reaperImage(reaperImageName),50 ExposedPorts: []string{string(listeningPort)},51 NetworkMode: Bridge,52 Labels: map[string]string{53 TestcontainerLabelIsReaper: "true",54 },55 SkipReaper: true,56 Mounts: Mounts(BindMount(dockerHost, "/var/run/docker.sock")),57 AutoRemove: true,58 WaitingFor: wait.ForListeningPort(listeningPort),59 }60 // include reaper-specific labels to the reaper container61 for k, v := range reaper.Labels() {62 req.Labels[k] = v63 }64 tcConfig := provider.Config()65 req.Privileged = tcConfig.RyukPrivileged66 // Attach reaper container to a requested network if it is specified67 if p, ok := provider.(*DockerProvider); ok {68 req.Networks = append(req.Networks, p.DefaultNetwork)69 }70 c, err := provider.RunContainer(ctx, req)71 if err != nil {72 return nil, err73 }74 endpoint, err := c.PortEndpoint(ctx, "8080", "")75 if err != nil {76 return nil, err77 }78 reaper.Endpoint = endpoint79 return reaper, nil80}81// Reaper is used to start a sidecar container that cleans up resources82type Reaper struct {83 Provider ReaperProvider84 SessionID string85 Endpoint string86}87// Connect runs a goroutine which can be terminated by sending true into the returned channel88func (r *Reaper) Connect() (chan bool, error) {89 conn, err := net.DialTimeout("tcp", r.Endpoint, 10*time.Second)90 if err != nil {91 return nil, fmt.Errorf("%w: Connecting to Ryuk on %s failed", err, r.Endpoint)92 }93 terminationSignal := make(chan bool)94 go func(conn net.Conn) {95 sock := bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))96 defer conn.Close()97 labelFilters := []string{}98 for l, v := range r.Labels() {99 labelFilters = append(labelFilters, fmt.Sprintf("label=%s=%s", l, v))100 }101 retryLimit := 3102 for retryLimit > 0 {103 retryLimit--104 sock.WriteString(strings.Join(labelFilters, "&"))105 sock.WriteString("\n")106 if err := sock.Flush(); err != nil {107 continue108 }109 resp, err := sock.ReadString('\n')110 if err != nil {111 continue112 }113 if resp == "ACK\n" {114 break115 }116 }117 <-terminationSignal118 }(conn)119 return terminationSignal, nil120}121// Labels returns the container labels to use so that this Reaper cleans them up122func (r *Reaper) Labels() map[string]string {123 return map[string]string{124 TestcontainerLabel: "true",125 TestcontainerLabelSessionID: r.SessionID,126 }127}128func extractDockerHost(ctx context.Context) (dockerHostPath string) {129 if dockerHostPath = os.Getenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE"); dockerHostPath != "" {130 return dockerHostPath131 }132 dockerHostPath = "/var/run/docker.sock"133 var hostRawURL string134 if h, ok := ctx.Value(dockerHostContextKey).(string); !ok || h == "" {135 return dockerHostPath136 } else {137 hostRawURL = h138 }139 var hostURL *url.URL140 if u, err := url.Parse(hostRawURL); err != nil {141 return dockerHostPath142 } else {...

Full Screen

Full Screen

reaper_test.go

Source:reaper_test.go Github

copy

Full Screen

...94}95func Test_ExtractDockerHost(t *testing.T) {96 t.Run("Docker Host as environment variable", func(t *testing.T) {97 t.Setenv("TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE", "/path/to/docker.sock")98 host := extractDockerHost(context.Background())99 assert.Equal(t, "/path/to/docker.sock", host)100 })101 t.Run("Default Docker Host", func(t *testing.T) {102 host := extractDockerHost(context.Background())103 assert.Equal(t, "/var/run/docker.sock", host)104 })105 t.Run("Malformed Docker Host is passed in context", func(t *testing.T) {106 ctx := context.Background()107 host := extractDockerHost(context.WithValue(ctx, dockerHostContextKey, "path-to-docker-sock"))108 assert.Equal(t, "/var/run/docker.sock", host)109 })110 t.Run("Malformed Schema Docker Host is passed in context", func(t *testing.T) {111 ctx := context.Background()112 host := extractDockerHost(context.WithValue(ctx, dockerHostContextKey, "http://path to docker sock"))113 assert.Equal(t, "/var/run/docker.sock", host)114 })115 t.Run("Unix Docker Host is passed in context", func(t *testing.T) {116 ctx := context.Background()117 host := extractDockerHost(context.WithValue(ctx, dockerHostContextKey, "unix:///this/is/a/sample.sock"))118 assert.Equal(t, "/this/is/a/sample.sock", host)119 })120}...

Full Screen

Full Screen

extractDockerHost

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 WaitingFor: wait.ForListeningPort("6379/tcp"),6 }7 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{8 })9 if err != nil {10 panic(err)11 }12 defer redisContainer.Terminate(ctx)13 ip, err := redisContainer.Host(ctx)14 if err != nil {15 panic(err)16 }17 port, err := redisContainer.MappedPort(ctx, "6379/tcp")18 if err != nil {19 panic(err)20 }21 fmt.Println(ip, port.Int())

Full Screen

Full Screen

extractDockerHost

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.ForListeningPort("5432/tcp"),7 }8 postgresqlContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer postgresqlContainer.Terminate(ctx)14 mappedPort, err := postgresqlContainer.MappedPort(ctx, "5432")15 if err != nil {16 log.Fatal(err)17 }18 containerIP, err := postgresqlContainer.Host(ctx)19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println(containerIP, mappedPort.Int())23}

Full Screen

Full Screen

extractDockerHost

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("Ready to accept connections"),7 }8 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer c.Terminate(ctx)14 ip, err := c.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := c.MappedPort(ctx, "80")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println(ip + ":" + port.Port())23}

Full Screen

Full Screen

extractDockerHost

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 dockerHost, err := testcontainers.DockerHost()4 if err != nil {5 panic(err)6 }7 fmt.Printf("Docker host: %s", dockerHost)8}

Full Screen

Full Screen

extractDockerHost

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 dockerHost, err := testcontainers.DockerEndpoint()4 if err != nil {5 panic(err)6 }7 fmt.Println(dockerHost)8}

Full Screen

Full Screen

extractDockerHost

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 dockerHost, err := testcontainers.DockerHost()4 if err != nil {5 fmt.Println("Error in extracting docker host")6 }7 fmt.Println(dockerHost)8}

Full Screen

Full Screen

extractDockerHost

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"80/tcp"},5 WaitingFor: wait.ForListeningPort("80/tcp"),6 }7 ctx, _ := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{8 })9 ip, _ := ctx.Host(ctx)10 port, _ := ctx.MappedPort(ctx, "80")11 fmt.Printf("Container IP: %s, Port: %s12 ctx.Terminate(ctx)13}

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