How to use BuildImage method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.BuildImage

docker.go

Source:docker.go Github

copy

Full Screen

...577 return TestContainersConfig{}578 }579 return cfg580}581// BuildImage will build and image from context and Dockerfile, then return the tag582func (p *DockerProvider) BuildImage(ctx context.Context, img ImageBuildInfo) (string, error) {583 repo := uuid.New()584 tag := uuid.New()585 repoTag := fmt.Sprintf("%s:%s", repo, tag)586 buildContext, err := img.GetContext()587 if err != nil {588 return "", err589 }590 buildOptions := types.ImageBuildOptions{591 BuildArgs: img.GetBuildArgs(),592 Dockerfile: img.GetDockerfile(),593 Context: buildContext,594 Tags: []string{repoTag},595 Remove: true,596 ForceRemove: true,597 }598 resp, err := p.client.ImageBuild(ctx, buildContext, buildOptions)599 if err != nil {600 return "", err601 }602 if img.ShouldPrintBuildLog() {603 termFd, isTerm := term.GetFdInfo(os.Stderr)604 err = jsonmessage.DisplayJSONMessagesStream(resp.Body, os.Stderr, termFd, isTerm, nil)605 if err != nil {606 return "", err607 }608 }609 // need to read the response from Docker, I think otherwise the image610 // might not finish building before continuing to execute here611 buf := new(bytes.Buffer)612 _, err = buf.ReadFrom(resp.Body)613 if err != nil {614 return "", err615 }616 _ = resp.Body.Close()617 return repoTag, nil618}619// CreateContainer fulfills a request for a container without starting it620func (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 error...

Full Screen

Full Screen

BuildImage

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"8080/tcp"},6 WaitingFor: wait.ForLog("Started"),7 }8 imageID, err := testcontainers.BuildImage(ctx, "./", "testcontainers/ryuk:0.3.0")9 if err != nil {10 log.Fatalf("Could not build image: %s", err)11 }12 fmt.Println("Image ID: ", imageID)13 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{14 })15 if err != nil {16 log.Fatalf("Could not create container: %s", err)17 }18 defer container.Terminate(ctx)19 containerID, err := container.GetContainerID(ctx)20 if err != nil {21 log.Fatalf("Could not get container ID: %s", err)22 }23 fmt.Println("Container ID: ", containerID)24 port, err := container.GetPort(ctx, "8080/tcp")25 if err != nil {26 log.Fatalf("Could not get port: %s", err)27 }28 fmt.Println("Port: ", port)

Full Screen

Full Screen

BuildImage

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 runContainer(ctx)5}6func buildImage(ctx context.Context) {7 testcontainers.BuildImage(ctx, "Dockerfile", "testcontainers-go", testcontainers.BuildImageOptions{8 BuildArgs: map[string]string{9 },10 })11}12func runImage(ctx context.Context) {13 req := testcontainers.ContainerRequest{14 ExposedPorts: []string{"80/tcp"},15 WaitingFor: wait.ForLog("server is ready"),16 }17 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{18 })19 if err != nil {20 log.Fatalf("Could not start container: %v", err)21 }22 defer c.Terminate(ctx)23 ip, err := c.Host(ctx)24 if err != nil {25 log.Fatalf("Could not get container IP: %v", err)26 }27 port, err := c.MappedPort(ctx, "80")28 if err != nil {29 log.Fatalf("Could not get container port: %v", err)30 }31 if err != nil {32 log.Fatalf("Could not send request: %v", err)33 }34 defer resp.Body.Close()35 body, err := ioutil.ReadAll(resp.Body)36 if err != nil {37 log.Fatalf("Could not read response: %v", err)38 }39 fmt.Println(string(body))40}41func runContainer(ctx context.Context) {42 file, err := os.Create("Dockerfile")43 if err != nil {44 log.Fatal(err)45 }46 defer file.Close()47 _, err = file.WriteString("FROM alpine

Full Screen

Full Screen

BuildImage

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("listening on TCP port 80"),7 Cmd: []string{"sh", "-c", "while true; do echo hello world; sleep 1; done"},8 }9 imageName, err := testcontainers.BuildImage(ctx, "Dockerfile", "testcontainers-go-example")10 if err != nil {11 panic(err)12 }13 fmt.Println(imageName)14 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{15 })16 if err != nil {17 panic(err)18 }19 defer container.Terminate(ctx)20 logs, err := container.GetContainerLogs(ctx, testcontainers.GetContainerLogsOptions{21 })22 if err != nil {23 panic(err)24 }25 _, err = io.Copy(os.Stdout, logs)26 if err != nil {27 panic(err)28 }29}

Full Screen

Full Screen

BuildImage

Using AI Code Generation

copy

Full Screen

1import (2const (3func main() {4 ctx := context.Background()5 req := testcontainers.ImageRequest{6 FromDockerfile: testcontainers.FromDockerfile{7 Context: os.Getenv("GOPATH"),8 },9 }10 image, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{11 ContainerRequest: testcontainers.ContainerRequest{12 WaitingFor: wait.ForLog("hello world"),13 },14 })15 if err != nil {16 log.Fatal(err)17 }18 id, err := image.ContainerID(ctx)19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println(id)23}24import (25const (26func main() {27 ctx := context.Background()28 req := testcontainers.ImageRequest{29 FromDockerfile: testcontainers.FromDockerfile{30 Context: os.Getenv("GOP

Full Screen

Full Screen

BuildImage

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.GenericContainerRequest{5 ContainerRequest: testcontainers.ContainerRequest{6 ExposedPorts: []string{"8080/tcp"},7 WaitingFor: wait.ForHTTP("/"),8 },9 }10 testContainer, err := testcontainers.GenericContainer(ctx, req)11 if err != nil {12 log.Fatal(err)13 }14 ip, err := testContainer.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := testContainer.MappedPort(ctx, "8080/tcp")19 if err != nil {20 log.Fatal(err)21 }22 err = testContainer.Terminate(ctx)23 if err != nil {24 log.Fatal(err)25 }26}27import (28func main() {29 ctx := context.Background()30 req := testcontainers.GenericContainerRequest{31 ContainerRequest: testcontainers.ContainerRequest{32 ExposedPorts: []string{"8080/tcp"},33 WaitingFor: wait.ForHTTP("/"),34 },35 }

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