How to use getDefaultNetwork method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.getDefaultNetwork

docker.go

Source:docker.go Github

copy

Full Screen

...620func (p *DockerProvider) CreateContainer(ctx context.Context, req ContainerRequest) (Container, error) {621 var err error622 // Make sure that bridge network exists623 // In case it is disabled we will create reaper_default network624 p.defaultNetwork, err = getDefaultNetwork(ctx, p.client)625 if err != nil {626 return nil, err627 }628 // If default network is not bridge make sure it is attached to the request629 // as container won't be attached to it automatically630 if p.defaultNetwork != Bridge {631 isAttached := false632 for _, net := range req.Networks {633 if net == p.defaultNetwork {634 isAttached = true635 break636 }637 }638 if !isAttached {639 req.Networks = append(req.Networks, p.defaultNetwork)640 }641 }642 exposedPortSet, exposedPortMap, err := nat.ParsePortSpecs(req.ExposedPorts)643 if err != nil {644 return nil, err645 }646 env := []string{}647 for envKey, envVar := range req.Env {648 env = append(env, envKey+"="+envVar)649 }650 if req.Labels == nil {651 req.Labels = make(map[string]string)652 }653 sessionID := uuid.New()654 var termSignal chan bool655 if !req.SkipReaper {656 r, err := NewReaper(ctx, sessionID.String(), p, req.ReaperImage)657 if err != nil {658 return nil, fmt.Errorf("%w: creating reaper failed", err)659 }660 termSignal, err = r.Connect()661 if err != nil {662 return nil, fmt.Errorf("%w: connecting to reaper failed", err)663 }664 for k, v := range r.Labels() {665 if _, ok := req.Labels[k]; !ok {666 req.Labels[k] = v667 }668 }669 }670 if err = req.Validate(); err != nil {671 return nil, err672 }673 var tag string674 var platform *specs.Platform675 if req.ShouldBuildImage() {676 tag, err = p.BuildImage(ctx, &req)677 if err != nil {678 return nil, err679 }680 } else {681 tag = req.Image682 if req.ImagePlatform != "" {683 p, err := platforms.Parse(req.ImagePlatform)684 if err != nil {685 return nil, fmt.Errorf("invalid platform %s: %w", req.ImagePlatform, err)686 }687 platform = &p688 }689 var shouldPullImage bool690 if req.AlwaysPullImage {691 shouldPullImage = true // If requested always attempt to pull image692 } else {693 image, _, err := p.client.ImageInspectWithRaw(ctx, tag)694 if err != nil {695 if client.IsErrNotFound(err) {696 shouldPullImage = true697 } else {698 return nil, err699 }700 }701 if platform != nil && (image.Architecture != platform.Architecture || image.Os != platform.OS) {702 shouldPullImage = true703 }704 }705 if shouldPullImage {706 pullOpt := types.ImagePullOptions{707 Platform: req.ImagePlatform, // may be empty708 }709 if req.RegistryCred != "" {710 pullOpt.RegistryAuth = req.RegistryCred711 }712 if err := p.attemptToPullImage(ctx, tag, pullOpt); err != nil {713 return nil, err714 }715 }716 }717 dockerInput := &container.Config{718 Entrypoint: req.Entrypoint,719 Image: tag,720 Env: env,721 ExposedPorts: exposedPortSet,722 Labels: req.Labels,723 Cmd: req.Cmd,724 Hostname: req.Hostname,725 User: req.User,726 }727 // prepare mounts728 mounts := mapToDockerMounts(req.Mounts)729 hostConfig := &container.HostConfig{730 ExtraHosts: req.ExtraHosts,731 PortBindings: exposedPortMap,732 Mounts: mounts,733 Tmpfs: req.Tmpfs,734 AutoRemove: req.AutoRemove,735 Privileged: req.Privileged,736 NetworkMode: req.NetworkMode,737 Resources: req.Resources,738 }739 endpointConfigs := map[string]*network.EndpointSettings{}740 // #248: Docker allows only one network to be specified during container creation741 // If there is more than one network specified in the request container should be attached to them742 // once it is created. We will take a first network if any specified in the request and use it to create container743 if len(req.Networks) > 0 {744 attachContainerTo := req.Networks[0]745 nw, err := p.GetNetwork(ctx, NetworkRequest{746 Name: attachContainerTo,747 })748 if err == nil {749 endpointSetting := network.EndpointSettings{750 Aliases: req.NetworkAliases[attachContainerTo],751 NetworkID: nw.ID,752 }753 endpointConfigs[attachContainerTo] = &endpointSetting754 }755 }756 networkingConfig := network.NetworkingConfig{757 EndpointsConfig: endpointConfigs,758 }759 resp, err := p.client.ContainerCreate(ctx, dockerInput, hostConfig, &networkingConfig, platform, req.Name)760 if err != nil {761 return nil, err762 }763 // #248: If there is more than one network specified in the request attach newly created container to them one by one764 if len(req.Networks) > 1 {765 for _, n := range req.Networks[1:] {766 nw, err := p.GetNetwork(ctx, NetworkRequest{767 Name: n,768 })769 if err == nil {770 endpointSetting := network.EndpointSettings{771 Aliases: req.NetworkAliases[n],772 }773 err = p.client.NetworkConnect(ctx, nw.ID, resp.ID, &endpointSetting)774 if err != nil {775 return nil, err776 }777 }778 }779 }780 c := &DockerContainer{781 ID: resp.ID,782 WaitingFor: req.WaitingFor,783 Image: tag,784 imageWasBuilt: req.ShouldBuildImage(),785 sessionID: sessionID,786 provider: p,787 terminationSignal: termSignal,788 skipReaper: req.SkipReaper,789 stopProducer: make(chan bool),790 logger: p.Logger,791 }792 return c, nil793}794// attemptToPullImage tries to pull the image while respecting the ctx cancellations.795// Besides, if the image cannot be pulled due to ErrorNotFound then no need to retry but terminate immediately.796func (p *DockerProvider) attemptToPullImage(ctx context.Context, tag string, pullOpt types.ImagePullOptions) error {797 var (798 err error799 pull io.ReadCloser800 )801 err = backoff.Retry(func() error {802 pull, err = p.client.ImagePull(ctx, tag, pullOpt)803 if err != nil {804 if _, ok := err.(errdefs.ErrNotFound); ok {805 return backoff.Permanent(err)806 }807 Logger.Printf("Failed to pull image: %s, will retry", err)808 return err809 }810 return nil811 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))812 if err != nil {813 return err814 }815 defer pull.Close()816 // download of docker image finishes at EOF of the pull request817 _, err = ioutil.ReadAll(pull)818 return err819}820// Health measure the healthiness of the provider. Right now we leverage the821// docker-client ping endpoint to see if the daemon is reachable.822func (p *DockerProvider) Health(ctx context.Context) (err error) {823 _, err = p.client.Ping(ctx)824 return825}826// RunContainer takes a RequestContainer as input and it runs a container via the docker sdk827func (p *DockerProvider) RunContainer(ctx context.Context, req ContainerRequest) (Container, error) {828 c, err := p.CreateContainer(ctx, req)829 if err != nil {830 return nil, err831 }832 if err := c.Start(ctx); err != nil {833 return c, fmt.Errorf("%w: could not start container", err)834 }835 return c, nil836}837// daemonHost gets the host or ip of the Docker daemon where ports are exposed on838// Warning: this is based on your Docker host setting. Will fail if using an SSH tunnel839// You can use the "TC_HOST" env variable to set this yourself840func (p *DockerProvider) daemonHost(ctx context.Context) (string, error) {841 if p.hostCache != "" {842 return p.hostCache, nil843 }844 host, exists := os.LookupEnv("TC_HOST")845 if exists {846 p.hostCache = host847 return p.hostCache, nil848 }849 // infer from Docker host850 url, err := url.Parse(p.client.DaemonHost())851 if err != nil {852 return "", err853 }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")973 }974 ip := strings.TrimSpace(string(stdout))975 if len(ip) == 0 {976 return "", errors.New("Failed to parse default gateway IP")977 }978 return string(ip), nil979}980func getDefaultNetwork(ctx context.Context, cli *client.Client) (string, error) {981 // Get list of available networks982 networkResources, err := cli.NetworkList(ctx, types.NetworkListOptions{})983 if err != nil {984 return "", err985 }986 reaperNetwork := ReaperDefault987 reaperNetworkExists := false988 for _, net := range networkResources {989 if net.Name == Bridge {990 return Bridge, nil991 }992 if net.Name == reaperNetwork {993 reaperNetworkExists = true994 }...

Full Screen

Full Screen

compose_provider.go

Source:compose_provider.go Github

copy

Full Screen

...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 == "" {352 return "", errors.New("failed to parse default gateway IP")353 }354 return ip, nil355}356func getDefaultNetwork(ctx context.Context, cli *client.Client) (string, error) {357 // Get list of available networks358 networkResources, err := cli.NetworkList(ctx, types.NetworkListOptions{})359 if err != nil {360 return "", err361 }362 reaperNetwork := ReaperDefault363 reaperNetworkExists := false364 for inx := range networkResources {365 if networkResources[inx].Name == Bridge {366 return Bridge, nil367 }368 if networkResources[inx].Name == reaperNetwork {369 reaperNetworkExists = true370 }...

Full Screen

Full Screen

getDefaultNetwork

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 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 network, err := testcontainers.DefaultNetwork(ctx)14 if err != nil {15 panic(err)16 }17 err = network.Connect(ctx, req, container)18 if err != nil {19 panic(err)20 }21 ip, err := container.Host(ctx)22 if err != nil {23 panic(err)24 }25 fmt.Println(ip)26}27import (28func main() {29 ctx := context.Background()30 req := testcontainers.ContainerRequest{31 ExposedPorts: []string{"80/tcp"},32 WaitingFor: wait.ForListeningPort("80/tcp"),33 }34 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{35 })36 if err != nil {37 panic(err)38 }39 network, err := testcontainers.DefaultNetwork(ctx)

Full Screen

Full Screen

getDefaultNetwork

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 panic(err)12 }13 defer redis.Terminate(ctx)14 ip, err := redis.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := redis.MappedPort(ctx, "6379")19 if err != nil {20 panic(err)21 }22 fmt.Printf("Redis is available at %s:%s", ip, port.Port())23}24import (25func main() {26 ctx := context.Background()27 req := testcontainers.ContainerRequest{28 ExposedPorts: []string{"6379/tcp"},29 WaitingFor: wait.ForListeningPort("6379/tcp"),30 }31 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{32 })33 if err != nil {34 panic(err)35 }36 defer redis.Terminate(ctx)37 ip, err := redis.Host(ctx)38 if err != nil {39 panic(err)40 }41 port, err := redis.MappedPort(ctx, "6379")42 if err != nil {43 panic(err)44 }45 fmt.Printf("Redis is available at %s:%s", ip, port.Port())46}47import (48func main() {49 ctx := context.Background()

Full Screen

Full Screen

getDefaultNetwork

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 network, _ := testcontainers.GenericNetwork(testcontainers.GenericNetworkRequest{4 NetworkRequest: testcontainers.NetworkRequest{5 },6 })7 fmt.Println(network)8}9import (10func main() {11 network, _ := testcontainers.GenericNetwork(testcontainers.GenericNetworkRequest{12 NetworkRequest: testcontainers.NetworkRequest{13 },14 })15 fmt.Println(network)16}17import (18func main() {19 network, _ := testcontainers.GenericNetwork(testcontainers.GenericNetworkRequest{20 NetworkRequest: testcontainers.NetworkRequest{21 },22 })23 fmt.Println(network)24}25import (26func main() {27 network, _ := testcontainers.GenericNetwork(testcontainers.GenericNetworkRequest{28 NetworkRequest: testcontainers.NetworkRequest{29 },30 })31 fmt.Println(network)32}33import (34func main() {35 network, _ := testcontainers.GenericNetwork(testcontainers.GenericNetworkRequest{36 NetworkRequest: testcontainers.NetworkRequest{37 },38 })39 fmt.Println(network)40}41import (42func main() {43 network, _ := testcontainers.GenericNetwork(testcontainers.GenericNetworkRequest{44 NetworkRequest: testcontainers.NetworkRequest{45 },

Full Screen

Full Screen

getDefaultNetwork

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"22/tcp"},6 WaitingFor: wait.ForListeningPort("22/tcp"),7 }8 network, err := testcontainers.GenericNetwork(ctx, testcontainers.GenericNetworkRequest{9 })10 if err != nil {11 log.Println(err)12 }13 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{14 })15 if err != nil {16 log.Println(err)17 }18 time.Sleep(10 * time.Second)19}

Full Screen

Full Screen

getDefaultNetwork

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 redisC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatalf("Could not start container: %v", err)12 }13 defer redisC.Terminate(ctx)14 ip, err := redisC.Host(ctx)15 if err != nil {16 log.Fatalf("Could not get container IP: %v", err)17 }18 port, err := redisC.MappedPort(ctx, "6379")19 if err != nil {20 log.Fatalf("Could not get container port: %v", err)21 }22 fmt.Println(ip)23 fmt.Println(port.Int())24}

Full Screen

Full Screen

getDefaultNetwork

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 network, err := testcontainers.GenericNetwork(context.Background(), testcontainers.GenericNetworkRequest{4 NetworkRequest: testcontainers.NetworkRequest{5 },6 })7 if err != nil {8 log.Fatal(err)9 }10 defer network.Terminate(context.Background())11 fmt.Println("Network Name: ", network.Name())12}13import (14func main() {15 network, err := testcontainers.GenericNetwork(context.Background(), testcontainers.GenericNetworkRequest{16 NetworkRequest: testcontainers.NetworkRequest{17 },18 })19 if err != nil {20 log.Fatal(err)21 }22 defer network.Terminate(context.Background())23 fmt.Println("Network Name: ", network.Name())24 network, err = testcontainers.GenericNetwork(context.Background(), testcontainers.GenericNetworkRequest{25 NetworkRequest: testcontainers.NetworkRequest{26 },27 })28 if err != nil {29 log.Fatal(err)30 }31 fmt.Println("Network Name: ", network.Name())32}33import (34func main() {35 network, err := testcontainers.GenericNetwork(context.Background(), testcontainers.GenericNetworkRequest{36 NetworkRequest: testcontainers.NetworkRequest{37 },38 })39 if err != nil {40 log.Fatal(err)41 }42 defer network.Terminate(context.Background())43 fmt.Println("Network Name: ", network.Name())44 network, err = testcontainers.GenericNetwork(context.Background(), testcontainers.GenericNetworkRequest{45 NetworkRequest: testcontainers.NetworkRequest{

Full Screen

Full Screen

getDefaultNetwork

Using AI Code Generation

copy

Full Screen

1import (2func TestContainer(t *testing.T) {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.Fatalf("Could not start container: %s", err)12 }13 defer postgresContainer.Terminate(ctx)14 ip, err := postgresContainer.Host(ctx)15 if err != nil {16 log.Fatalf("Could not get container IP: %s", err)17 }18 port, err := postgresContainer.MappedPort(ctx, "5432")19 if err != nil {20 log.Fatalf("Could not get container port: %s", err)21 }22 fmt.Printf("Container IP: %s, Container Port: %s", ip, port.Port())23}

Full Screen

Full Screen

getDefaultNetwork

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 network, _ := testcontainers.GenericNetwork(testcontainers.GenericNetworkRequest{4 })5 network.Create()6 fmt.Println("Network created")7 network.Remove()8 fmt.Println("Network removed")9}10import (11func main() {12 ctx := context.Background()13 req := testcontainers.ContainerRequest{14 Cmd: []string{"sh", "-c", "while true; do sleep 1; done"},15 }16 container, _ := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{17 })18 ipAddress, _ := container.Host(ctx)19 fmt.Println("IP Address of the container: " + ipAddress)20 container.Terminate(ctx)21}

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