Best Testcontainers-go code snippet using testcontainers.inAContainer
docker.go
Source:docker.go
...854 switch url.Scheme {855 case "http", "https", "tcp":856 p.hostCache = url.Hostname()857 case "unix", "npipe":858 if inAContainer() {859 ip, err := p.GetGatewayIP(ctx)860 if err != nil {861 // fallback to getDefaultGatewayIP862 ip, err = getDefaultGatewayIP()863 if err != nil {864 ip = "localhost"865 }866 }867 p.hostCache = ip868 } else {869 p.hostCache = "localhost"870 }871 default:872 return "", errors.New("Could not determine host through env or docker host")873 }874 return p.hostCache, nil875}876// CreateNetwork returns the object representing a new network identified by its name877func (p *DockerProvider) CreateNetwork(ctx context.Context, req NetworkRequest) (Network, error) {878 var err error879 // Make sure that bridge network exists880 // In case it is disabled we will create reaper_default network881 p.defaultNetwork, err = getDefaultNetwork(ctx, p.client)882 if req.Labels == nil {883 req.Labels = make(map[string]string)884 }885 nc := types.NetworkCreate{886 Driver: req.Driver,887 CheckDuplicate: req.CheckDuplicate,888 Internal: req.Internal,889 EnableIPv6: req.EnableIPv6,890 Attachable: req.Attachable,891 Labels: req.Labels,892 }893 sessionID := uuid.New()894 var termSignal chan bool895 if !req.SkipReaper {896 r, err := NewReaper(ctx, sessionID.String(), p, req.ReaperImage)897 if err != nil {898 return nil, fmt.Errorf("%w: creating network reaper failed", err)899 }900 termSignal, err = r.Connect()901 if err != nil {902 return nil, fmt.Errorf("%w: connecting to network reaper failed", err)903 }904 for k, v := range r.Labels() {905 if _, ok := req.Labels[k]; !ok {906 req.Labels[k] = v907 }908 }909 }910 response, err := p.client.NetworkCreate(ctx, req.Name, nc)911 if err != nil {912 return &DockerNetwork{}, err913 }914 n := &DockerNetwork{915 ID: response.ID,916 Driver: req.Driver,917 Name: req.Name,918 terminationSignal: termSignal,919 provider: p,920 }921 return n, nil922}923// GetNetwork returns the object representing the network identified by its name924func (p *DockerProvider) GetNetwork(ctx context.Context, req NetworkRequest) (types.NetworkResource, error) {925 networkResource, err := p.client.NetworkInspect(ctx, req.Name, types.NetworkInspectOptions{926 Verbose: true,927 })928 if err != nil {929 return types.NetworkResource{}, err930 }931 return networkResource, err932}933func (p *DockerProvider) GetGatewayIP(ctx context.Context) (string, error) {934 // Use a default network as defined in the DockerProvider935 if p.defaultNetwork == "" {936 var err error937 p.defaultNetwork, err = getDefaultNetwork(ctx, p.client)938 if err != nil {939 return "", err940 }941 }942 nw, err := p.GetNetwork(ctx, NetworkRequest{Name: p.defaultNetwork})943 if err != nil {944 return "", err945 }946 var ip string947 for _, config := range nw.IPAM.Config {948 if config.Gateway != "" {949 ip = config.Gateway950 break951 }952 }953 if ip == "" {954 return "", errors.New("Failed to get gateway IP from network settings")955 }956 return ip, nil957}958func inAContainer() bool {959 // see https://github.com/testcontainers/testcontainers-java/blob/3ad8d80e2484864e554744a4800a81f6b7982168/core/src/main/java/org/testcontainers/dockerclient/DockerClientConfigUtils.java#L15960 if _, err := os.Stat("/.dockerenv"); err == nil {961 return true962 }963 return false964}965// deprecated966// see https://github.com/testcontainers/testcontainers-java/blob/main/core/src/main/java/org/testcontainers/dockerclient/DockerClientConfigUtils.java#L46967func getDefaultGatewayIP() (string, error) {968 // see https://github.com/testcontainers/testcontainers-java/blob/3ad8d80e2484864e554744a4800a81f6b7982168/core/src/main/java/org/testcontainers/dockerclient/DockerClientConfigUtils.java#L27969 cmd := exec.Command("sh", "-c", "ip route|awk '/default/ { print $3 }'")970 stdout, err := cmd.Output()971 if err != nil {972 return "", errors.New("Failed to detect docker host")...
compose_provider.go
Source:compose_provider.go
...280 switch parsedURL.Scheme {281 case "http", "https", "tcp":282 p.hostCache = parsedURL.Hostname()283 case "unix", "npipe":284 if inAContainer() {285 ip, err := p.GetGatewayIP(ctx)286 if err != nil {287 // fallback to getDefaultGatewayIP288 ip, err = getDefaultGatewayIP()289 if err != nil {290 ip = localhost291 }292 }293 p.hostCache = ip294 } else {295 p.hostCache = localhost296 }297 default:298 return "", errors.New("could not determine host through env or docker host")299 }300 return p.hostCache, nil301}302// GetNetwork returns the object representing the network identified by its name303func (p *DockerProvider) GetNetwork(ctx context.Context, req NetworkRequest) (types.NetworkResource, error) {304 networkResource, err := p.client.NetworkInspect(ctx, req.Name, types.NetworkInspectOptions{305 Verbose: true,306 })307 if err != nil {308 return types.NetworkResource{}, err309 }310 return networkResource, err311}312func (p *DockerProvider) GetGatewayIP(ctx context.Context) (string, error) {313 // Use a default network as defined in the DockerProvider314 var err error315 if p.defaultNetwork == "" {316 p.defaultNetwork, err = getDefaultNetwork(ctx, p.client)317 if err != nil {318 return "", err319 }320 }321 nw, err := p.GetNetwork(ctx, NetworkRequest{Name: p.defaultNetwork})322 if err != nil {323 return "", err324 }325 var ip string326 for _, config := range nw.IPAM.Config {327 if config.Gateway != "" {328 ip = config.Gateway329 break330 }331 }332 if ip == "" {333 return "", errors.New("failed to get gateway IP from network settings")334 }335 return ip, nil336}337func inAContainer() bool {338 if _, err := os.Stat("/.dockerenv"); err == nil {339 return true340 }341 return false342}343// deprecated344func getDefaultGatewayIP() (string, error) {345 cmd := exec.Command("sh", "-c", "ip route|awk '/default/ { print $3 }'")346 stdout, err := cmd.Output()347 if err != nil {348 return "", errors.New("failed to detect docker host")349 }350 ip := strings.TrimSpace(string(stdout))351 if ip == "" {...
inAContainer
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 Cmd: []string{"sleep", "3600"},6 WaitingFor: wait.ForLog("running"),7 ExposedPorts: []string{"80/tcp"},8 }9 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 panic(err)13 }14 defer container.Terminate(ctx)15 ip, err := container.Host(ctx)16 if err != nil {17 panic(err)18 }19 port, err := container.MappedPort(ctx, "80")20 if err != nil {21 panic(err)22 }23 fmt.Println(ip, port.Int())24}
inAContainer
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"5432/tcp"},6 WaitingFor: wait.ForListeningPort("5432/tcp"),7 }8 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 ip, err := postgresContainer.Host(ctx)14 if err != nil {15 log.Fatal(err)16 }17 port, err := postgresContainer.MappedPort(ctx, "5432")18 if err != nil {19 log.Fatal(err)20 }21 fmt.Println(ip)22 fmt.Println(port.Int())23 time.Sleep(5 * time.Second)24}
inAContainer
Using AI Code Generation
1import (2func main() {3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"80/tcp"},5 WaitingFor: wait.ForLog("ready").WithStartupTimeout(60 * time.Second),6 }7 ctx := context.Background()8}9import (10func main() {11 req := testcontainers.ContainerRequest{12 ExposedPorts: []string{"80/tcp"},13 WaitingFor: wait.ForLog("ready").WithStartupTimeout(60 * time.Second),14 }15 ctx := context.Background()16}
inAContainer
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"8091/tcp", "8092/tcp", "8093/tcp", "8094/tcp", "11207/tcp", "11210/tcp", "11211/tcp", "18091/tcp", "18092/tcp", "18093/tcp", "18094/tcp"},6 WaitingFor: wait.ForLog("The default credentials are").WithStartupTimeout(5 * time.Minute),7 }8 couchbase, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer couchbase.Terminate(ctx)14 ip, err := couchbase.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 fmt.Println(ip)19 internalPort, err := couchbase.MappedPort(ctx, "8091")20 if err != nil {21 log.Fatal(err)22 }23 fmt.Println(internalPort.Int())24}25import (26func main() {27 ctx := context.Background()28 req := testcontainers.ContainerRequest{29 ExposedPorts: []string{"8091/tcp", "8092/tcp", "8093/tcp", "8094/tcp", "11207/tcp", "11210/tcp", "11211/tcp", "18091/tcp", "18092/tcp", "18093/tcp", "18094/tcp"},30 WaitingFor: wait.ForLog("The default credentials are").WithStartupTimeout(5 * time.Minute),31 }32 couchbase, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{33 })34 if err != nil {35 log.Fatal(err)36 }
inAContainer
Using AI Code Generation
1import (2func main() {3 cli, err := client.NewEnvClient()4 if err != nil {5 panic(err)6 }7 ctx := context.Background()8 out, err := cli.ImagePull(ctx, "docker.io/library/redis:latest", types.ImagePullOptions{})9 if err != nil {10 panic(err)11 }12 io.Copy(os.Stdout, out)13 resp, err := cli.ContainerCreate(ctx, &container.Config{14 }, nil, nil, nil, "")15 if err != nil {16 panic(err)17 }18 if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {19 panic(err)20 }21 out, err = cli.ContainerLogs(ctx, resp.ID, types.ContainerLogsOptions{ShowStdout: true})22 if err != nil {23 panic(err)24 }25 io.Copy(os.Stdout, out)26 if err := cli.ContainerStop(ctx, resp.ID, &timeout); err != nil {27 panic(err)28 }29 if err := cli.ContainerRemove(ctx, resp.ID, types.ContainerRemoveOptions{}); err != nil {30 panic(err)31 }32}33import (34func main() {35 cli, err := client.NewEnvClient()36 if err != nil {37 panic(err)38 }39 ctx := context.Background()40 out, err := cli.ImagePull(ctx, "docker.io/library/redis:latest", types.ImagePullOptions{})41 if err != nil {42 panic(err)43 }44 io.Copy(os.Stdout, out)45 resp, err := cli.ContainerCreate(ctx, &container.Config{46 }, &container.HostConfig{
inAContainer
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 Cmd: []string{"sleep", "5m"},6 ExposedPorts: []string{"80/tcp"},7 WaitingFor: wait.ForLog("Listening on port 80"),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 %s is listening on %s:%s", c.GetContainerID(), ip, port.Port())24}25func inAContainer() bool {26 return os.Getenv("TESTCONTAINERS_RYUK_DISABLED") == "true"27}28func waitForContainerStart(ctx context.Context, c testcontainers.Container) {29 for {30 _, err := c.Exec(ctx, []string{"true"})31 if err == nil {32 }33 select {34 case <-ctx.Done():35 log.Fatal("Timed out waiting for container to start")36 case <-time.After(100 * time.Millisecond):37 }38 }39}40func waitForContainerStop(ctx context.Context, c testcontainers.Container) {41 for {
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!!