How to use CreateContainer method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.CreateContainer

e2e_util_test.go

Source:e2e_util_test.go Github

copy

Full Screen

1package generate_test2import (3 "bytes"4 "context"5 "encoding/json"6 "fmt"7 "github.com/pkg/errors"8 log "github.com/sirupsen/logrus"9 "github.com/testcontainers/testcontainers-go"10 "github.com/testcontainers/testcontainers-go/wait"11 "io/ioutil"12 "net/http"13 "os"14 "strings"15 "time"16)17type ServiceStack struct {18 ServerHost string19 ServerPort int20 StorageHost string21 StoragePort int22 PostgresHost string23 PostgresPort int24 AdminJwt string25}26func WithBackupRepositoryDockerStack(test func(ServiceStack)) {27 ctx := context.Background()28 postgres, postgresHost, postgresPort := createPostgresContainer(ctx)29 storage, storageHost, storagePort := createMinioContainer(ctx)30 server, serverHost, serverPort := createServerContainer(ctx, postgresHost, postgresPort, storageHost, storagePort)31 jwt := loginToServer(serverHost, serverPort, "admin", "admin")32 defer storage.Terminate(ctx)33 defer postgres.Terminate(ctx)34 defer server.Terminate(ctx)35 test(ServiceStack{36 ServerHost: serverHost,37 ServerPort: serverPort,38 StorageHost: storageHost,39 StoragePort: storagePort,40 PostgresHost: postgresHost,41 PostgresPort: postgresPort,42 AdminJwt: jwt,43 })44}45// loginToServer is getting a JWT token for given username and password46func loginToServer(serverHost string, serverPort int, user string, password string) string {47 postBody, _ := json.Marshal(map[string]string{48 "username": user,49 "password": password,50 })51 body := bytes.NewBuffer(postBody)52 response, err := http.Post(fmt.Sprintf("http://%s:%v/api/stable/auth/login", serverHost, serverPort), "application/json", body)53 if err != nil {54 log.Fatal(errors.Wrap(err, "Cannot make authorization request"))55 }56 if response.StatusCode > 200 {57 log.Fatalf("Cannot authenticate user login=%s, password=%s, response code: %v", user, password, response.StatusCode)58 }59 responseBuffer, readErr := ioutil.ReadAll(response.Body)60 if readErr != nil {61 log.Fatal(errors.Wrap(readErr, "Cannot read response"))62 }63 var parsedResponse = struct {64 Data struct {65 Token string `json:"token"`66 } `json:"data"`67 }{}68 if err := json.Unmarshal(responseBuffer, &parsedResponse); err != nil {69 log.Fatalf("Cannot parse server response: %v, Error: %s", string(responseBuffer), err.Error())70 }71 return parsedResponse.Data.Token72}73// Backup Repository server container on-demand74func createServerContainer(ctx context.Context, postgresHost string, postgresPort int, minioHost string, minioPort int) (testcontainers.Container, string, int) {75 version := os.Getenv("TEST_BACKUP_REPOSITORY_VERSION")76 req := testcontainers.ContainerRequest{77 Image: "ghcr.io/riotkit-org/backup-repository:" + version,78 Env: map[string]string{79 "BR_DB_HOSTNAME": postgresHost,80 "BR_DB_USERNAME": "rojava",81 "BR_DB_PASSWORD": "rojava",82 "BR_DB_NAME": "emma-goldman",83 "BR_DB_PORT": fmt.Sprintf("%v", postgresPort),84 "BR_STORAGE_DRIVER_URL": fmt.Sprintf("s3://orwell1984?endpoint=%s:%v&disableSSL=true&s3ForcePathStyle=true&region=eu-central-1", minioHost, minioPort),85 "AWS_ACCESS_KEY_ID": "AKIAIOSFODNN7EXAMPLE",86 "AWS_SECRET_ACCESS_KEY": "wJaFuCKtnFEMI/CApItaliSM/bPxRfiCYEXAMPLEKEY",87 "BR_JWT_SECRET_KEY": "anarchism-is-the-key",88 "BR_HEALTH_CHECK_KEY": "to-cooperate-for-whole-world",89 "BR_LOG_LEVEL": "debug",90 "GIN_MODE": "debug",91 "BR_CONFIG_LOCAL_PATH": "/mnt/filesystem-config",92 "BR_CONFIG_PROVIDER": "filesystem",93 },94 ExposedPorts: []string{"8080/tcp"},95 WaitingFor: wait.ForHTTP("/ready?code=to-cooperate-for-whole-world").WithPort("8080").WithPollInterval(time.Second),96 Networks: []string{"backup-repository-e2e"},97 NetworkAliases: map[string][]string{98 "backup-repository-e2e": {99 "server",100 },101 },102 }103 wd, _ := os.Getwd()104 req.Mounts = testcontainers.ContainerMounts{105 testcontainers.ContainerMount{106 Source: testcontainers.GenericBindMountSource{HostPath: wd + "/../.build"},107 Target: "/mnt",108 ReadOnly: false,109 },110 }111 return createContainer(ctx, req, 8080)112}113func createMinioContainer(ctx context.Context) (testcontainers.Container, string, int) {114 version := os.Getenv("TEST_MINIO_VERSION")115 req := testcontainers.ContainerRequest{116 Image: "bitnami/minio:" + version,117 Env: map[string]string{118 "MINIO_DEFAULT_BUCKETS": "orwell1984",119 "MINIO_ROOT_USER": "AKIAIOSFODNN7EXAMPLE",120 "MINIO_ROOT_PASSWORD": "wJaFuCKtnFEMI/CApItaliSM/bPxRfiCYEXAMPLEKEY",121 },122 ExposedPorts: []string{"9000/tcp"},123 WaitingFor: wait.ForLog("Console:"),124 Networks: []string{"backup-repository-e2e"},125 NetworkAliases: map[string][]string{126 "backup-repository-e2e": {127 "storage",128 },129 },130 }131 return createContainer(ctx, req, 9000)132}133// PostgreSQL container on-demand134func createPostgresContainer(ctx context.Context) (testcontainers.Container, string, int) {135 version := os.Getenv("TEST_POSTGRES_VERSION")136 req := testcontainers.ContainerRequest{137 Image: "postgres:" + version,138 Env: map[string]string{139 "POSTGRES_USER": "rojava",140 "POSTGRES_PASSWORD": "rojava",141 "POSTGRES_DB": "emma-goldman",142 },143 ExposedPorts: []string{"5432/tcp"},144 WaitingFor: wait.ForLog("database system is ready to accept connections"),145 Networks: []string{"backup-repository-e2e"},146 NetworkAliases: map[string][]string{147 "backup-repository-e2e": {148 "postgres",149 },150 },151 }152 return createContainer(ctx, req, 5432)153}154// MySQL container on-demand155func CreateMariaDBContainer(ctx context.Context) (testcontainers.Container, string, int) {156 version := os.Getenv("TEST_MARIADB_VERSION")157 req := testcontainers.ContainerRequest{158 Image: "mariadb:" + version,159 Env: map[string]string{160 "MARIADB_ROOT_PASSWORD": "mutual-aid",161 "MARIADB_USER": "rojava",162 "MARIADB_PASSWORD": "rojava",163 "MARIADB_DATABASE": "emma_goldman",164 },165 ExposedPorts: []string{"3306/tcp"},166 WaitingFor: wait.ForLog("MariaDB init process done. Ready for start up."),167 Networks: []string{"backup-repository-e2e"},168 NetworkAliases: map[string][]string{169 "backup-repository-e2e": {170 "mariadb",171 },172 },173 }174 return createContainer(ctx, req, 3306)175}176func createContainer(ctx context.Context, req testcontainers.ContainerRequest, mappedPort int) (testcontainers.Container, string, int) {177 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{178 ContainerRequest: req,179 Started: true,180 })181 if err != nil {182 log.Fatal(errors.Wrap(err, "Cannot create container"))183 }184 ip, ipErr := container.ContainerIP(ctx)185 if ipErr != nil {186 log.Fatal(errors.Wrap(err, "Cannot get container IP"))187 }188 return container, strings.ReplaceAll(ip, "/", ""), mappedPort189}190func writeDefinitionForLaterSnippetGeneration(content string) {191 _ = ioutil.WriteFile("../.build/definition.yaml", []byte(strings.ReplaceAll(content, "\t", " ")), 0755)192}...

Full Screen

Full Screen

sqlserver.go

Source:sqlserver.go Github

copy

Full Screen

...31func (req ContainerRequest) WithNetworkAlias(network, alias string) ContainerRequest {32 canned.AddNetworkAlias(&req.GenericContainerRequest, network, alias)33 return req34}35// CreateContainer creates a SQL Server for Linux container36func CreateContainer(ctx context.Context, req ContainerRequest) (*Container, error) {37 if req.Env == nil {38 req.Env = make(map[string]string)39 }40 req.Env["ACCEPT_EULA"] = "Y"41 if req.Image == "" {42 req.Image = image43 req.Env["MSSQL_PID"] = "Express"44 }45 req.GenericContainerRequest.Image = req.Image46 if req.ExposedPorts == nil {47 req.ExposedPorts = []string{exposedPort}48 }49 if req.Username == "" {50 req.Username = username51 }52 if req.Password == "" {53 return nil, errors.New("a password must be provided")54 }55 req.Env["SA_PASSWORD"] = req.Password56 if req.WaitingFor == nil {57 req.WaitingFor = wait.ForSQL(exposedPort, "sqlserver", func(port nat.Port) string {58 return fmt.Sprintf("sqlserver://%s:%s@localhost:%s", req.Username, req.Password, port.Port())59 }).Timeout(time.Minute)60 }61 provider, err := req.ProviderType.GetProvider()62 if err != nil {63 return nil, err64 }65 result := &Container{66 req: req,67 }68 req.Started = false69 if result.Container, err = provider.CreateContainer(ctx, req.ContainerRequest); err != nil {70 return result, errors.Wrap(err, "could not create container")71 }72 if req.Logger != nil {73 if err = result.Container.StartLogProducer(ctx); err != nil {74 return result, errors.Wrap(err, "could not start log producer")75 }76 result.Container.FollowOutput(*req.Logger)77 }78 if err = result.Container.Start(ctx); err != nil {79 return result, errors.Wrap(err, "could not start container")80 }81 return result, nil82}83// GoConnectionString returns a connection string suitable for usage in Go...

Full Screen

Full Screen

genericapi.go

Source:genericapi.go Github

copy

Full Screen

...28func (req ContainerRequest) WithNetworkAlias(network, alias string) ContainerRequest {29 canned.AddNetworkAlias(&req.GenericContainerRequest, network, alias)30 return req31}32// CreateContainer creates and starts a container and assumes it contains an HTTP API33func CreateContainer(ctx context.Context, req ContainerRequest) (*Container, error) {34 if req.Port == "" {35 req.Port = defaultPort36 }37 if req.Image == "" {38 return nil, errors.New("an image name is required")39 }40 req.GenericContainerRequest.Image = req.Image41 if req.ExposedPorts == nil {42 req.ExposedPorts = []string{string(req.Port)}43 }44 if req.LivenessEndpoint == "" {45 req.LivenessEndpoint = defaultLivenessEndpoint46 }47 if req.WaitingFor == nil {48 req.WaitingFor = wait.ForHTTP(req.LivenessEndpoint).49 WithPort(req.Port)50 }51 provider, err := req.ProviderType.GetProvider()52 if err != nil {53 return nil, err54 }55 result := &Container{56 req: req,57 }58 req.Started = false59 if result.Container, err = provider.CreateContainer(ctx, req.ContainerRequest); err != nil {60 return result, errors.Wrap(err, "Error creating container")61 }62 if err = result.Container.Start(ctx); err != nil {63 return result, errors.Wrap(err, "Error starting container")64 }65 return result, nil66}67// URL builds an URL that can be used to interact with the container's HTTP API68func (c Container) URL(ctx context.Context) (string, error) {69 host, err := c.Container.Host(ctx)70 if err != nil {71 return "", errors.Wrap(err, "Error reading container host name")72 }73 port, err := c.Container.MappedPort(ctx, c.req.Port)...

Full Screen

Full Screen

CreateContainer

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 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer redisContainer.Terminate(ctx)14 redisHost, err := redisContainer.Host(ctx)15 if err != nil {16 panic(err)17 }18 redisPort, err := redisContainer.MappedPort(ctx, "6379/tcp")19 if err != nil {20 panic(err)21 }22 fmt.Printf("redis is available at %s:%s23", redisHost, redisPort.Port())24}

Full Screen

Full Screen

CreateContainer

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.ForLog("database system is ready to accept connections"),7 }8 postgres, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer postgres.Terminate(ctx)14 ip, err := postgres.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := postgres.MappedPort(ctx, "5432")19 if err != nil {20 log.Fatal(err)21 }22 log.Printf("postgres is available on %s:%s", ip, port.Port())23 time.Sleep(10 * time.Second)24}

Full Screen

Full Screen

CreateContainer

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 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal("Could not start container: %s", err)12 }13 defer redisContainer.Terminate(ctx)14 redisHost, err := redisContainer.Host(ctx)15 if err != nil {16 log.Fatal("Could not get host: %s", err)17 }18 redisPort, err := redisContainer.MappedPort(ctx, "6379/tcp")19 if err != nil {20 log.Fatal("Could not get port: %s", err)21 }22 fmt.Printf("Host: %s, Port: %s", redisHost, redisPort.Port())23}

Full Screen

Full Screen

CreateContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())4 if err != nil {5 panic(err)6 }7 ctx := context.Background()8 resp, err := cli.ContainerCreate(ctx, &container.Config{9 Cmd: []string{"top"},10 }, nil, nil, nil, "testcontainer")11 if err != nil {12 panic(err)13 }14 if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {15 panic(err)16 }17 inspect, err := cli.ContainerInspect(ctx, resp.ID)18 if err != nil {19 panic(err)20 }21 fmt.Println(inspect.ID)22 if err := cli.ContainerStop(ctx, resp.ID, nil); err != nil {23 panic(err)24 }25 if err := cli.ContainerRemove(ctx, resp.ID, types.ContainerRemoveOptions{}); err != nil {26 panic(err)27 }28 resp, err = cli.ContainerCreate(ctx, &container.Config{29 Cmd: []string{"top"},30 }, &container.HostConfig{31 }, &network.NetworkingConfig{32 EndpointsConfig: map[string]*network.EndpointSettings{33 "network-test": &network.EndpointSettings{},34 },35 }, nil, "testcontainer")36 if err != nil {37 panic(err)38 }39 if err := cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}); err != nil {40 panic(err)41 }42 inspect, err = cli.ContainerInspect(ctx, resp.ID)43 if err != nil {44 panic(err)45 }

Full Screen

Full Screen

CreateContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"27017/tcp"},6 WaitingFor: wait.ForLog("waiting for connections on port"),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 port, err := c.MappedPort(ctx, "27017")15 if err != nil {16 log.Fatal(err)17 }18 ip, err := c.Host(ctx)19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println("ip address: ", ip)23 fmt.Println("port: ", port.Int())24 time.Sleep(5 * time.Minute)25}

Full Screen

Full Screen

CreateContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 Cmd: []string{"sleep", "1h"},6 WaitingFor: wait.ForLog("listening"),7 }8 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatalf("Could not start container: %v", err)12 }13 defer c.Terminate(ctx)14 ip, err := c.Host(ctx)15 if err != nil {16 log.Fatalf("Could not get container IP: %v", err)17 }18 fmt.Println(ip)19 port, err := c.MappedPort(ctx, "80")20 if err != nil {21 log.Fatalf("Could not get container port: %v", err)22 }23 fmt.Println(port.Int())24 cmd := exec.Command("docker", "exec", c.GetContainerID(), "ls", "-l")25 if err := cmd.Run(); err != nil {26 log.Fatalf("Could not run command inside container: %v", err)27 }28}

Full Screen

Full Screen

CreateContainer

Using AI Code Generation

copy

Full Screen

1func main() {2 ctx := context.Background()3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"6379/tcp"},5 WaitingFor: wait.ForLog("Ready to accept connections"),6 }7 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{8 })9 if err != nil {10 log.Fatal(err)11 }12 defer redisContainer.Terminate(ctx)13 ip, err := redisContainer.Host(ctx)14 if err != nil {15 log.Fatal(err)16 }17 port, err := redisContainer.MappedPort(ctx, "6379/tcp")18 if err != nil {19 log.Fatal(err)20 }21 fmt.Println(ip, port.Int())22}23func main() {24 ctx := context.Background()25 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{26 ContainerRequest: testcontainers.ContainerRequest{27 ExposedPorts: []string{"6379/tcp"},28 WaitingFor: wait.ForLog("Ready to accept connections"),29 },30 })31 if err != nil {32 log.Fatal(err)33 }34 defer redisContainer.Terminate(ctx)35 ip, err := redisContainer.Host(ctx)36 if err != nil {37 log.Fatal(err)38 }39 port, err := redisContainer.MappedPort(ctx, "6379/tcp")40 if err != nil {41 log.Fatal(err)42 }43 fmt.Println(ip, port.Int())44}

Full Screen

Full Screen

CreateContainer

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 ctx := context.Background()5 req := testcontainers.ContainerRequest{6 ExposedPorts: []string{"6379/tcp"},7 WaitingFor: wait.ForListeningPort("6379/tcp"),8 }9 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 log.Fatal(err)13 }14 defer redis.Terminate(ctx)15 redisPort, err := redis.MappedPort(ctx, "6379")16 if err != nil {17 log.Fatal(err)18 }19 redisHost, err := redis.Host(ctx)20 if err != nil {21 log.Fatal(err)22 }23 redisIP, err := redis.ContainerIP(ctx)24 if err != nil {25 log.Fatal(err)26 }27 fmt.Println(redisPort.Int(), redisHost, redisIP)28 time.Sleep(10 * time.Second)29}

Full Screen

Full Screen

CreateContainer

Using AI Code Generation

copy

Full Screen

1func main() {2 ctx := context.Background()3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"6379/tcp"},5 WaitingFor: wait.ForLog("Ready to accept connections"),6 }7 redisContainer, _ := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{8 })9 defer redisContainer.Terminate(ctx)10 port, _ := redisContainer.MappedPort(ctx, "6379")11 fmt.Println(port.Int())12}13type ContainerRequest struct {14}15type Container interface {16 Terminate(context.Context) error17 Start(context.Context) error18 Exec(context.Context, []string, io.Reader, io.Writer, io.Writer, bool) (int, error)19 MappedPort(context.Context, nat.Port) (nat.Port, error)20 Host(context.Context) (string, error)

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