How to use printReaperBanner method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.printReaperBanner

docker.go

Source:docker.go Github

copy

Full Screen

...811 req.Labels[k] = v812 }813 }814 } else if !isReaperContainer {815 p.printReaperBanner("container")816 }817 if err = req.Validate(); err != nil {818 return nil, err819 }820 var tag string821 var platform *specs.Platform822 if req.ShouldBuildImage() {823 tag, err = p.BuildImage(ctx, &req)824 if err != nil {825 return nil, err826 }827 } else {828 tag = req.Image829 if req.ImagePlatform != "" {830 p, err := platforms.Parse(req.ImagePlatform)831 if err != nil {832 return nil, fmt.Errorf("invalid platform %s: %w", req.ImagePlatform, err)833 }834 platform = &p835 }836 var shouldPullImage bool837 if req.AlwaysPullImage {838 shouldPullImage = true // If requested always attempt to pull image839 } else {840 image, _, err := p.client.ImageInspectWithRaw(ctx, tag)841 if err != nil {842 if client.IsErrNotFound(err) {843 shouldPullImage = true844 } else {845 return nil, err846 }847 }848 if platform != nil && (image.Architecture != platform.Architecture || image.Os != platform.OS) {849 shouldPullImage = true850 }851 }852 if shouldPullImage {853 pullOpt := types.ImagePullOptions{854 Platform: req.ImagePlatform, // may be empty855 }856 if req.RegistryCred != "" {857 pullOpt.RegistryAuth = req.RegistryCred858 }859 if err := p.attemptToPullImage(ctx, tag, pullOpt); err != nil {860 return nil, err861 }862 }863 }864 exposedPorts := req.ExposedPorts865 if len(exposedPorts) == 0 && !req.NetworkMode.IsContainer() {866 image, _, err := p.client.ImageInspectWithRaw(ctx, tag)867 if err != nil {868 return nil, err869 }870 for p, _ := range image.ContainerConfig.ExposedPorts {871 exposedPorts = append(exposedPorts, string(p))872 }873 }874 exposedPortSet, exposedPortMap, err := nat.ParsePortSpecs(exposedPorts)875 if err != nil {876 return nil, err877 }878 dockerInput := &container.Config{879 Entrypoint: req.Entrypoint,880 Image: tag,881 Env: env,882 ExposedPorts: exposedPortSet,883 Labels: req.Labels,884 Cmd: req.Cmd,885 Hostname: req.Hostname,886 User: req.User,887 }888 // prepare mounts889 mounts := mapToDockerMounts(req.Mounts)890 hostConfig := &container.HostConfig{891 ExtraHosts: req.ExtraHosts,892 PortBindings: exposedPortMap,893 Binds: req.Binds,894 Mounts: mounts,895 Tmpfs: req.Tmpfs,896 AutoRemove: req.AutoRemove,897 Privileged: req.Privileged,898 NetworkMode: req.NetworkMode,899 Resources: req.Resources,900 ShmSize: req.ShmSize,901 CapAdd: req.CapAdd,902 CapDrop: req.CapDrop,903 }904 endpointConfigs := map[string]*network.EndpointSettings{}905 // #248: Docker allows only one network to be specified during container creation906 // If there is more than one network specified in the request container should be attached to them907 // once it is created. We will take a first network if any specified in the request and use it to create container908 if len(req.Networks) > 0 {909 attachContainerTo := req.Networks[0]910 nw, err := p.GetNetwork(ctx, NetworkRequest{911 Name: attachContainerTo,912 })913 if err == nil {914 endpointSetting := network.EndpointSettings{915 Aliases: req.NetworkAliases[attachContainerTo],916 NetworkID: nw.ID,917 }918 endpointConfigs[attachContainerTo] = &endpointSetting919 }920 }921 networkingConfig := network.NetworkingConfig{922 EndpointsConfig: endpointConfigs,923 }924 resp, err := p.client.ContainerCreate(ctx, dockerInput, hostConfig, &networkingConfig, platform, req.Name)925 if err != nil {926 return nil, err927 }928 // #248: If there is more than one network specified in the request attach newly created container to them one by one929 if len(req.Networks) > 1 {930 for _, n := range req.Networks[1:] {931 nw, err := p.GetNetwork(ctx, NetworkRequest{932 Name: n,933 })934 if err == nil {935 endpointSetting := network.EndpointSettings{936 Aliases: req.NetworkAliases[n],937 }938 err = p.client.NetworkConnect(ctx, nw.ID, resp.ID, &endpointSetting)939 if err != nil {940 return nil, err941 }942 }943 }944 }945 c := &DockerContainer{946 ID: resp.ID,947 WaitingFor: req.WaitingFor,948 Image: tag,949 imageWasBuilt: req.ShouldBuildImage(),950 sessionID: sessionID,951 provider: p,952 terminationSignal: termSignal,953 skipReaper: req.SkipReaper,954 stopProducer: make(chan bool),955 logger: p.Logger,956 }957 for _, f := range req.Files {958 err := c.CopyFileToContainer(ctx, f.HostFilePath, f.ContainerFilePath, f.FileMode)959 if err != nil {960 return nil, fmt.Errorf("can't copy %s to container: %w", f.HostFilePath, err)961 }962 }963 return c, nil964}965func (p *DockerProvider) findContainerByName(ctx context.Context, name string) (*types.Container, error) {966 if name == "" {967 return nil, nil968 }969 // Note that, 'name' filter will use regex to find the containers970 filter := filters.NewArgs(filters.Arg("name", fmt.Sprintf("^%s$", name)))971 containers, err := p.client.ContainerList(ctx, types.ContainerListOptions{Filters: filter})972 if err != nil {973 return nil, err974 }975 if len(containers) > 0 {976 return &containers[0], nil977 }978 return nil, nil979}980func (p *DockerProvider) ReuseOrCreateContainer(ctx context.Context, req ContainerRequest) (Container, error) {981 c, err := p.findContainerByName(ctx, req.Name)982 if err != nil {983 return nil, err984 }985 if c == nil {986 return p.CreateContainer(ctx, req)987 }988 sessionID := sessionID()989 var termSignal chan bool990 if !req.SkipReaper {991 r, err := NewReaper(context.WithValue(ctx, dockerHostContextKey, p.host), sessionID.String(), p, req.ReaperImage)992 if err != nil {993 return nil, fmt.Errorf("%w: creating reaper failed", err)994 }995 termSignal, err = r.Connect()996 if err != nil {997 return nil, fmt.Errorf("%w: connecting to reaper failed", err)998 }999 } else {1000 p.printReaperBanner("container")1001 }1002 dc := &DockerContainer{1003 ID: c.ID,1004 WaitingFor: req.WaitingFor,1005 Image: c.Image,1006 sessionID: sessionID,1007 provider: p,1008 terminationSignal: termSignal,1009 skipReaper: req.SkipReaper,1010 stopProducer: make(chan bool),1011 logger: p.Logger,1012 isRunning: c.State == "running",1013 }1014 return dc, nil1015}1016// attemptToPullImage tries to pull the image while respecting the ctx cancellations.1017// Besides, if the image cannot be pulled due to ErrorNotFound then no need to retry but terminate immediately.1018func (p *DockerProvider) attemptToPullImage(ctx context.Context, tag string, pullOpt types.ImagePullOptions) error {1019 var (1020 err error1021 pull io.ReadCloser1022 )1023 err = backoff.Retry(func() error {1024 pull, err = p.client.ImagePull(ctx, tag, pullOpt)1025 if err != nil {1026 if _, ok := err.(errdefs.ErrNotFound); ok {1027 return backoff.Permanent(err)1028 }1029 Logger.Printf("Failed to pull image: %s, will retry", err)1030 return err1031 }1032 return nil1033 }, backoff.WithContext(backoff.NewExponentialBackOff(), ctx))1034 if err != nil {1035 return err1036 }1037 defer pull.Close()1038 // download of docker image finishes at EOF of the pull request1039 _, err = ioutil.ReadAll(pull)1040 return err1041}1042// Health measure the healthiness of the provider. Right now we leverage the1043// docker-client ping endpoint to see if the daemon is reachable.1044func (p *DockerProvider) Health(ctx context.Context) (err error) {1045 _, err = p.client.Ping(ctx)1046 return1047}1048// RunContainer takes a RequestContainer as input and it runs a container via the docker sdk1049func (p *DockerProvider) RunContainer(ctx context.Context, req ContainerRequest) (Container, error) {1050 c, err := p.CreateContainer(ctx, req)1051 if err != nil {1052 return nil, err1053 }1054 if err := c.Start(ctx); err != nil {1055 return c, fmt.Errorf("%w: could not start container", err)1056 }1057 return c, nil1058}1059// Config provides the TestContainersConfig read from $HOME/.testcontainers.properties or1060// the environment variables1061func (p *DockerProvider) Config() TestContainersConfig {1062 return p.config1063}1064// daemonHost gets the host or ip of the Docker daemon where ports are exposed on1065// Warning: this is based on your Docker host setting. Will fail if using an SSH tunnel1066// You can use the "TC_HOST" env variable to set this yourself1067func (p *DockerProvider) daemonHost(ctx context.Context) (string, error) {1068 if p.hostCache != "" {1069 return p.hostCache, nil1070 }1071 host, exists := os.LookupEnv("TC_HOST")1072 if exists {1073 p.hostCache = host1074 return p.hostCache, nil1075 }1076 // infer from Docker host1077 url, err := url.Parse(p.client.DaemonHost())1078 if err != nil {1079 return "", err1080 }1081 switch url.Scheme {1082 case "http", "https", "tcp":1083 p.hostCache = url.Hostname()1084 case "unix", "npipe":1085 if inAContainer() {1086 ip, err := p.GetGatewayIP(ctx)1087 if err != nil {1088 // fallback to getDefaultGatewayIP1089 ip, err = getDefaultGatewayIP()1090 if err != nil {1091 ip = "localhost"1092 }1093 }1094 p.hostCache = ip1095 } else {1096 p.hostCache = "localhost"1097 }1098 default:1099 return "", errors.New("Could not determine host through env or docker host")1100 }1101 return p.hostCache, nil1102}1103// CreateNetwork returns the object representing a new network identified by its name1104func (p *DockerProvider) CreateNetwork(ctx context.Context, req NetworkRequest) (Network, error) {1105 var err error1106 // Make sure that bridge network exists1107 // In case it is disabled we will create reaper_default network1108 if p.DefaultNetwork == "" {1109 if p.DefaultNetwork, err = p.getDefaultNetwork(ctx, p.client); err != nil {1110 return nil, err1111 }1112 }1113 if req.Labels == nil {1114 req.Labels = make(map[string]string)1115 }1116 nc := types.NetworkCreate{1117 Driver: req.Driver,1118 CheckDuplicate: req.CheckDuplicate,1119 Internal: req.Internal,1120 EnableIPv6: req.EnableIPv6,1121 Attachable: req.Attachable,1122 Labels: req.Labels,1123 IPAM: req.IPAM,1124 }1125 var termSignal chan bool1126 if !req.SkipReaper {1127 sessionID := sessionID()1128 r, err := NewReaper(context.WithValue(ctx, dockerHostContextKey, p.host), sessionID.String(), p, req.ReaperImage)1129 if err != nil {1130 return nil, fmt.Errorf("%w: creating network reaper failed", err)1131 }1132 termSignal, err = r.Connect()1133 if err != nil {1134 return nil, fmt.Errorf("%w: connecting to network reaper failed", err)1135 }1136 for k, v := range r.Labels() {1137 if _, ok := req.Labels[k]; !ok {1138 req.Labels[k] = v1139 }1140 }1141 } else {1142 p.printReaperBanner("network")1143 }1144 response, err := p.client.NetworkCreate(ctx, req.Name, nc)1145 if err != nil {1146 return &DockerNetwork{}, err1147 }1148 n := &DockerNetwork{1149 ID: response.ID,1150 Driver: req.Driver,1151 Name: req.Name,1152 terminationSignal: termSignal,1153 provider: p,1154 }1155 return n, nil1156}1157// GetNetwork returns the object representing the network identified by its name1158func (p *DockerProvider) GetNetwork(ctx context.Context, req NetworkRequest) (types.NetworkResource, error) {1159 networkResource, err := p.client.NetworkInspect(ctx, req.Name, types.NetworkInspectOptions{1160 Verbose: true,1161 })1162 if err != nil {1163 return types.NetworkResource{}, err1164 }1165 return networkResource, err1166}1167func (p *DockerProvider) GetGatewayIP(ctx context.Context) (string, error) {1168 // Use a default network as defined in the DockerProvider1169 if p.DefaultNetwork == "" {1170 var err error1171 p.DefaultNetwork, err = p.getDefaultNetwork(ctx, p.client)1172 if err != nil {1173 return "", err1174 }1175 }1176 nw, err := p.GetNetwork(ctx, NetworkRequest{Name: p.DefaultNetwork})1177 if err != nil {1178 return "", err1179 }1180 var ip string1181 for _, config := range nw.IPAM.Config {1182 if config.Gateway != "" {1183 ip = config.Gateway1184 break1185 }1186 }1187 if ip == "" {1188 return "", errors.New("Failed to get gateway IP from network settings")1189 }1190 return ip, nil1191}1192func (p *DockerProvider) printReaperBanner(resource string) {1193 ryukDisabledMessage := `1194 **********************************************************************************************1195 Ryuk has been disabled for the ` + resource + `. This can cause unexpected behavior in your environment.1196 More on this: https://golang.testcontainers.org/features/garbage_collector/1197 **********************************************************************************************`1198 p.Logger.Printf(ryukDisabledMessage)1199}1200func inAContainer() bool {1201 // see https://github.com/testcontainers/testcontainers-java/blob/3ad8d80e2484864e554744a4800a81f6b7982168/core/src/main/java/org/testcontainers/dockerclient/DockerClientConfigUtils.java#L151202 if _, err := os.Stat("/.dockerenv"); err == nil {1203 return true1204 }1205 return false1206}...

Full Screen

Full Screen

printReaperBanner

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 provider, err := testcontainers.NewDockerProvider()10 if err != nil {11 panic(err)12 }13 container, err := provider.CreateContainer(ctx, req)14 if err != nil {15 panic(err)16 }17 err = provider.StartContainer(ctx, container)18 if err != nil {19 panic(err)20 }21 ip, err := provider.GetContainerIP(ctx, container)22 if err != nil {23 panic(err)24 }25 fmt.Println(ip)26 err = provider.StopContainer(ctx, container)27 if err != nil {28 panic(err)29 }30 err = provider.RemoveContainer(ctx, container)31 if err != nil {32 panic(err)33 }34}35import (36func main() {37 ctx := context.Background()38 req := testcontainers.ContainerRequest{39 Cmd: []string{"echo", "Hello world!"},40 ExposedPorts: []string{"80/tcp"},41 WaitingFor: wait.ForLog("Hello world!"),42 }43 provider, err := testcontainers.NewDockerProvider()44 if err != nil {45 panic(err)46 }47 container, err := provider.CreateContainer(ctx, req)48 if err != nil {49 panic(err)50 }51 err = provider.StartContainer(ctx, container

Full Screen

Full Screen

printReaperBanner

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"8080"},6 WaitingFor: wait.ForLog("Started!"),7 }8 ryukContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer ryukContainer.Terminate(ctx)14}15import (16func main() {17 ctx := context.Background()18 req := testcontainers.ContainerRequest{19 ExposedPorts: []string{"8080"},20 WaitingFor: wait.ForLog("Started!"),21 }22 ryukContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{23 })24 if err != nil {25 panic(err)26 }27 defer ryukContainer.Terminate(ctx)28 fmt.Println("Ryuk container started")29}30import (31func main() {32 ctx := context.Background()33 req := testcontainers.ContainerRequest{34 ExposedPorts: []string{"8080"},35 WaitingFor: wait.ForLog("Started!"),36 }37 ryukContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{38 })39 if err != nil {40 panic(err)41 }42 defer ryukContainer.Terminate(ctx)43 fmt.Println("Ryuk container started")44 fmt.Println(ryukContainer.Get

Full Screen

Full Screen

printReaperBanner

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 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/tcp")20 if err != nil {21 log.Fatal(err)22 }23 fmt.Println(ip, port.Int())24}

Full Screen

Full Screen

printReaperBanner

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(testcontainers.PrintReaperBanner())4}5import (6func main() {7 fmt.Println(testcontainers.PrintReaperBanner())8}9import (10func main() {11 fmt.Println(testcontainers.PrintReaperBanner())12}13import (14func main() {15 fmt.Println(testcontainers.PrintReaperBanner())16}17import (18func main() {19 fmt.Println(testcontainers.PrintReaperBanner())20}21import (22func main() {23 fmt.Println(testcontainers.PrintReaperBanner())24}25import (26func main() {27 fmt.Println(testcontainers.PrintReaperBanner())28}29import (30func main() {31 fmt.Println(testcontainers.PrintReaperBanner())32}33import (34func main() {35 fmt.Println(testcontainers.PrintReaperBanner())36}37import (38func main()

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