How to use Exec method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.Exec

integration_npm_execute_scripts_test.go

Source:integration_npm_execute_scripts_test.go Github

copy

Full Screen

...23 err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "runScriptsWithOptions"), tempDir)24 if err != nil {25 t.Fatal("Failed to copy test project.")26 }27 //workaround to use test script util it is possible to set workdir for Exec call28 testScript := `#!/bin/sh29cd /test30/piperbin/piper npmExecuteScripts --runScripts=start --scriptOptions=--tag,tag1 >test-log.txt 2>&131`32 ioutil.WriteFile(filepath.Join(tempDir, "runPiper.sh"), []byte(testScript), 0700)33 reqNode := testcontainers.ContainerRequest{34 Image: "node:12-slim",35 Cmd: []string{"tail", "-f"},36 BindMounts: map[string]string{37 pwd: "/piperbin",38 tempDir: "/test",39 },40 }41 nodeContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{42 ContainerRequest: reqNode,43 Started: true,44 })45 code, err := nodeContainer.Exec(ctx, []string{"sh", "/test/runPiper.sh"})46 assert.NoError(t, err)47 assert.Equal(t, 0, code)48 content, err := ioutil.ReadFile(filepath.Join(tempDir, "/test-log.txt"))49 if err != nil {50 t.Fatal("Could not read test-log.txt.", err)51 }52 output := string(content)53 assert.Contains(t, output, "info npmExecuteScripts - running command: npm run start -- --tag tag1")54 assert.Contains(t, output, "info npmExecuteScripts - [ '--tag', 'tag1' ]")55}56func TestRegistrySetInFlags(t *testing.T) {57 t.Parallel()58 ctx := context.Background()59 pwd, err := os.Getwd()60 assert.NoError(t, err, "Getting current working directory failed.")61 pwd = filepath.Dir(pwd)62 // using custom createTmpDir function to avoid issues with symlinks on Docker for Mac63 tempDir, err := createTmpDir("")64 defer os.RemoveAll(tempDir) // clean up65 assert.NoError(t, err, "Error when creating temp dir")66 err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "registrySetInFlags"), tempDir)67 if err != nil {68 t.Fatal("Failed to copy test project.")69 }70 //workaround to use test script util it is possible to set workdir for Exec call71 testScript := `#!/bin/sh72cd /test73/piperbin/piper npmExecuteScripts --install --runScripts=ci-build,ci-backend-unit-test --defaultNpmRegistry=https://foo.bar >test-log.txt 2>&174`75 ioutil.WriteFile(filepath.Join(tempDir, "runPiper.sh"), []byte(testScript), 0700)76 reqNode := testcontainers.ContainerRequest{77 Image: "node:12-slim",78 Cmd: []string{"tail", "-f"},79 BindMounts: map[string]string{80 pwd: "/piperbin",81 tempDir: "/test",82 },83 }84 nodeContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{85 ContainerRequest: reqNode,86 Started: true,87 })88 code, err := nodeContainer.Exec(ctx, []string{"sh", "/test/runPiper.sh"})89 assert.NoError(t, err)90 assert.Equal(t, 0, code)91 content, err := ioutil.ReadFile(filepath.Join(tempDir, "/test-log.txt"))92 if err != nil {93 t.Fatal("Could not read test-log.txt.", err)94 }95 output := string(content)96 assert.Contains(t, output, "info npmExecuteScripts - https://foo.bar")97}98func TestRegistrySetInNpmrc(t *testing.T) {99 t.Parallel()100 ctx := context.Background()101 pwd, err := os.Getwd()102 assert.NoError(t, err, "Getting current working directory failed.")103 pwd = filepath.Dir(pwd)104 // using custom createTmpDir function to avoid issues with symlinks on Docker for Mac105 tempDir, err := createTmpDir("")106 defer os.RemoveAll(tempDir) // clean up107 assert.NoError(t, err, "Error when creating temp dir")108 err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "registrySetInNpmrc"), tempDir)109 if err != nil {110 t.Fatal("Failed to copy test project.")111 }112 //workaround to use test script util it is possible to set workdir for Exec call113 testScript := `#!/bin/sh114cd /test115/piperbin/piper npmExecuteScripts --install --runScripts=ci-build,ci-backend-unit-test >test-log.txt 2>&1116`117 ioutil.WriteFile(filepath.Join(tempDir, "runPiper.sh"), []byte(testScript), 0700)118 reqNode := testcontainers.ContainerRequest{119 Image: "node:12-slim",120 Cmd: []string{"tail", "-f"},121 BindMounts: map[string]string{122 pwd: "/piperbin",123 tempDir: "/test",124 },125 }126 nodeContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{127 ContainerRequest: reqNode,128 Started: true,129 })130 code, err := nodeContainer.Exec(ctx, []string{"sh", "/test/runPiper.sh"})131 assert.NoError(t, err)132 assert.Equal(t, 0, code)133 content, err := ioutil.ReadFile(filepath.Join(tempDir, "/test-log.txt"))134 if err != nil {135 t.Fatal("Could not read test-log.txt.", err)136 }137 output := string(content)138 assert.Contains(t, output, "info npmExecuteScripts - https://example.com")139}140func TestRegistryWithTwoModules(t *testing.T) {141 t.Parallel()142 ctx := context.Background()143 pwd, err := os.Getwd()144 assert.NoError(t, err, "Getting current working directory failed.")145 pwd = filepath.Dir(pwd)146 // using custom createTmpDir function to avoid issues with symlinks on Docker for Mac147 tempDir, err := createTmpDir("")148 defer os.RemoveAll(tempDir) // clean up149 assert.NoError(t, err, "Error when creating temp dir")150 err = copyDir(filepath.Join(pwd, "integration", "testdata", "TestNpmIntegration", "registryWithTwoModules"), tempDir)151 if err != nil {152 t.Fatal("Failed to copy test project.")153 }154 //workaround to use test script util it is possible to set workdir for Exec call155 testScript := `#!/bin/sh156cd /test157/piperbin/piper npmExecuteScripts --install --runScripts=ci-build,ci-backend-unit-test --defaultNpmRegistry=https://foo.bar >test-log.txt 2>&1158`159 ioutil.WriteFile(filepath.Join(tempDir, "runPiper.sh"), []byte(testScript), 0700)160 reqNode := testcontainers.ContainerRequest{161 Image: "node:12-slim",162 Cmd: []string{"tail", "-f"},163 BindMounts: map[string]string{164 pwd: "/piperbin",165 tempDir: "/test",166 },167 }168 nodeContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{169 ContainerRequest: reqNode,170 Started: true,171 })172 code, err := nodeContainer.Exec(ctx, []string{"sh", "/test/runPiper.sh"})173 assert.NoError(t, err)174 assert.Equal(t, 0, code)175 content, err := ioutil.ReadFile(filepath.Join(tempDir, "/test-log.txt"))176 if err != nil {177 t.Fatal("Could not read test-log.txt.", err)178 }179 output := string(content)180 assert.Contains(t, output, "info npmExecuteScripts - https://example.com")181 assert.Contains(t, output, "info npmExecuteScripts - https://foo.bar")182}...

Full Screen

Full Screen

exec_test.go

Source:exec_test.go Github

copy

Full Screen

...9 "github.com/docker/go-connections/nat"10 "github.com/testcontainers/testcontainers-go"11 "github.com/testcontainers/testcontainers-go/wait"12)13func ExampleExecStrategy() {14 ctx := context.Background()15 req := testcontainers.ContainerRequest{16 Image: "localstack/localstack:latest",17 WaitingFor: wait.ForExec([]string{"awslocal", "dynamodb", "list-tables"}),18 }19 localstack, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{20 ContainerRequest: req,21 Started: true,22 })23 if err != nil {24 panic(err)25 }26 defer localstack.Terminate(ctx) // nolint: errcheck27 // Here you have a running container28}29type mockExecTarget struct {30 waitDuration time.Duration31 successAfter time.Time32 exitCode int33 failure error34}35func (st mockExecTarget) Host(_ context.Context) (string, error) {36 return "", errors.New("not implemented")37}38func (st mockExecTarget) MappedPort(_ context.Context, n nat.Port) (nat.Port, error) {39 return n, errors.New("not implemented")40}41func (st mockExecTarget) Logs(_ context.Context) (io.ReadCloser, error) {42 return nil, errors.New("not implemented")43}44func (st mockExecTarget) Exec(ctx context.Context, _ []string) (int, error) {45 time.Sleep(st.waitDuration)46 if err := ctx.Err(); err != nil {47 return st.exitCode, err48 }49 if !st.successAfter.IsZero() && time.Now().After(st.successAfter) {50 return 0, st.failure51 }52 return st.exitCode, st.failure53}54func (st mockExecTarget) State(_ context.Context) (*types.ContainerState, error) {55 return nil, errors.New("not implemented")56}57func TestExecStrategyWaitUntilReady(t *testing.T) {58 target := mockExecTarget{}59 wg := wait.NewExecStrategy([]string{"true"}).60 WithStartupTimeout(30 * time.Second)61 err := wg.WaitUntilReady(context.Background(), target)62 if err != nil {63 t.Fatal(err)64 }65}66func TestExecStrategyWaitUntilReadyForExec(t *testing.T) {67 target := mockExecTarget{}68 wg := wait.ForExec([]string{"true"})69 err := wg.WaitUntilReady(context.Background(), target)70 if err != nil {71 t.Fatal(err)72 }73}74func TestExecStrategyWaitUntilReady_MultipleChecks(t *testing.T) {75 target := mockExecTarget{76 exitCode: 10,77 successAfter: time.Now().Add(2 * time.Second),78 }79 wg := wait.NewExecStrategy([]string{"true"}).80 WithPollInterval(500 * time.Millisecond)81 err := wg.WaitUntilReady(context.Background(), target)82 if err != nil {83 t.Fatal(err)84 }85}86func TestExecStrategyWaitUntilReady_DeadlineExceeded(t *testing.T) {87 ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond)88 defer cancel()89 target := mockExecTarget{90 waitDuration: 1 * time.Second,91 }92 wg := wait.NewExecStrategy([]string{"true"})93 err := wg.WaitUntilReady(ctx, target)94 if err != context.DeadlineExceeded {95 t.Fatal(err)96 }97}98func TestExecStrategyWaitUntilReady_CustomExitCode(t *testing.T) {99 target := mockExecTarget{100 exitCode: 10,101 }102 wg := wait.NewExecStrategy([]string{"true"}).WithExitCodeMatcher(func(exitCode int) bool {103 return exitCode == 10104 })105 err := wg.WaitUntilReady(context.Background(), target)106 if err != nil {107 t.Fatal(err)108 }109}...

Full Screen

Full Screen

integration_cli_test.go

Source:integration_cli_test.go Github

copy

Full Screen

...24 err = copyDir(filepath.Join(pwd, "integration", "testdata", t.Name()), tempDir)25 if err != nil {26 t.Fatal("Failed to copy test project.")27 }28 //workaround to use test script util it is possible to set workdir for Exec call29 testScript := `#!/bin/sh30cd /test31/piperbin/piper karmaExecuteTests32`33 ioutil.WriteFile(filepath.Join(tempDir, "runPiper.sh"), []byte(testScript), 0700)34 networkName := "sidecar-" + uuid.New().String()35 reqNode := testcontainers.ContainerRequest{36 Image: "node:lts-stretch",37 Cmd: []string{"tail", "-f"},38 BindMounts: map[string]string{39 pwd: "/piperbin",40 tempDir: "/test",41 },42 Networks: []string{networkName},43 NetworkAliases: map[string][]string{networkName: {"karma"}},44 }45 reqSel := testcontainers.ContainerRequest{46 Image: "selenium/standalone-chrome",47 Networks: []string{networkName},48 NetworkAliases: map[string][]string{networkName: {"selenium"}},49 }50 provider, err := testcontainers.ProviderDocker.GetProvider()51 assert.NoError(t, err)52 network, err := provider.CreateNetwork(ctx, testcontainers.NetworkRequest{Name: networkName, CheckDuplicate: true})53 if err != nil {54 t.Fatal(err)55 }56 defer network.Remove(ctx)57 nodeContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{58 ContainerRequest: reqNode,59 Started: true,60 })61 if err != nil {62 t.Fatal(err)63 }64 defer nodeContainer.Terminate(ctx)65 selContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{66 ContainerRequest: reqSel,67 Started: true,68 })69 if err != nil {70 t.Fatal(err)71 }72 defer selContainer.Terminate(ctx)73 // cannot use piper command directly since it is not possible to set Workdir for Exec call74 // workaround use shell call in container (see above)75 //piperOptions := []string{76 // "karmaExecuteTests",77 // "--help",78 //}79 //code, err := nodeContainer.Exec(ctx, append([]string{"/data/piper"}, piperOptions...))80 code, err := nodeContainer.Exec(ctx, []string{"sh", "/test/runPiper.sh"})81 assert.NoError(t, err)82 assert.Equal(t, 0, code)83}...

Full Screen

Full Screen

Exec

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"3306/tcp"},6 Env: map[string]string{7 },8 WaitingFor: wait.ForLog("port: 3306 MySQL Community Server - GPL").WithOccurrence(1),9 }10 db, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{11 })12 if err != nil {13 log.Fatal(err)14 }15 defer db.Terminate(ctx)16 dbHost, err := db.Host(ctx)17 if err != nil {18 log.Fatal(err)19 }20 dbPort, err := db.MappedPort(ctx, "3306")21 if err != nil {22 log.Fatal(err)23 }24 dbURL := fmt.Sprintf("root:password@tcp(%s:%s)/", dbHost, dbPort.Port())25 dbConn, err := sql.Open("mysql", dbURL)26 if err != nil {27 log.Fatal(err)28 }29 defer dbConn.Close()30 _, err = dbConn.Exec("CREATE DATABASE test")31 if err != nil {32 log.Fatal(err)33 }34 dbURL = fmt.Sprintf("root:password@tcp(%s:%s)/test", dbHost, dbPort.Port())35 dbConn, err = sql.Open("mysql", dbURL)36 if err != nil {37 log.Fatal(err)38 }39 defer dbConn.Close()40 _, err = dbConn.Exec("CREATE TABLE test (id INT, name VARCHAR(255))")41 if err != nil {42 log.Fatal(err)43 }44 _, err = dbConn.Exec("INSERT INTO test VALUES (1, 'test')")45 if err != nil {46 log.Fatal(err)47 }48 rows, err := dbConn.Query("SELECT * FROM test")49 if err != nil {50 log.Fatal(err)51 }52 defer rows.Close()53 for rows.Next() {54 err = rows.Scan(&id, &name)

Full Screen

Full Screen

Exec

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"3306/tcp"},6 WaitingFor: wait.ForListeningPort("3306/tcp"),7 }8 mysqlContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer mysqlContainer.Terminate(ctx)14 host, err := mysqlContainer.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := mysqlContainer.MappedPort(ctx, "3306")19 if err != nil {20 panic(err)21 }22 dsn := fmt.Sprintf("root:password@tcp(%s:%s)/", host, port.Port())23 db, err := sql.Open("mysql", dsn)24 if err != nil {25 panic(err)26 }27 defer db.Close()28 _, err = db.Exec("CREATE DATABASE test")29 if err != nil {30 panic(err)31 }32}

Full Screen

Full Screen

Exec

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.ForHTTP("/"),7 }

Full Screen

Full Screen

Exec

Using AI Code Generation

copy

Full Screen

1func main() {2 ctx := context.Background()3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"5432/tcp"},5 WaitingFor: wait.ForLog("database system is ready to accept connections"),6 }7 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{8 })9 if err != nil {10 panic(err)11 }12 defer postgresContainer.Terminate(ctx)13 ip, err := postgresContainer.Host(ctx)14 if err != nil {15 panic(err)16 }17 port, err := postgresContainer.MappedPort(ctx, "5432")18 if err != nil {19 panic(err)20 }21 fmt.Printf("postgres is available at %s:%s", ip, port.Port())22}23func main() {24 ctx := context.Background()25 req := testcontainers.ContainerRequest{26 ExposedPorts: []string{"5432/tcp"},27 WaitingFor: wait.ForLog("database system is ready to accept connections"),28 }29 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{30 })31 if err != nil {32 panic(err)33 }34 defer postgresContainer.Terminate(ctx)35 ip, err := postgresContainer.Host(ctx)36 if err != nil {37 panic(err)38 }39 port, err := postgresContainer.MappedPort(ctx, "5432")40 if err != nil {41 panic(err)42 }43 fmt.Printf("postgres is available at %s:%s", ip, port.Port())44}45func main() {46 ctx := context.Background()47 req := testcontainers.ContainerRequest{48 ExposedPorts: []string{"5432/tcp"},49 WaitingFor: wait.ForLog("database system is ready to accept connections"),50 }51 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{52 })53 if err != nil {54 panic(err)55 }

Full Screen

Full Screen

Exec

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req := testcontainers.ContainerRequest{4 Cmd: []string{"sh", "-c", "while true; do sleep 1; done"},5 ExposedPorts: []string{"80/tcp"},6 WaitingFor: wait.ForLog("listening on port 80"),7 }8 ctx := context.Background()9 cont, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 log.Fatal(err)13 }14 ip, err := cont.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := cont.MappedPort(ctx, "80")19 if err != nil {20 log.Fatal(err)21 }22 id, err := cont.ContainerID(ctx)23 if err != nil {24 log.Fatal(err)25 }26 fmt.Println("Container ID: ", id)27 fmt.Println("Container IP: ", ip)28 fmt.Println("Container Port: ", port.Int())29 err = cont.Terminate(ctx)30 if err != nil {31 log.Fatal(err)32 }33 cmd := exec.Command("docker", "exec", "-it", id, "ping", ip)34 err = cmd.Run()35 if err != nil {36 log.Fatal(err)37 }38 cmd = exec.Command("docker", "exec", "-it", id, "ping", "google.com")39 err = cmd.Run()40 if err != nil {41 log.Fatal(err)42 }43 logs, err := cont.Logs(ctx)44 if err != nil {45 log.Fatal(err)46 }47 fmt.Println("Container Logs: ", strings.Split(string

Full Screen

Full Screen

Exec

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"3306/tcp"},5 WaitingFor: wait.ForLog("port: 3306 MySQL Community Server - GPL"),6 }7 ctx := context.Background()8 mysql, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer mysql.Terminate(ctx)14 ip, err := mysql.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := mysql.MappedPort(ctx, "3306")19 if err != nil {20 panic(err)21 }22 fmt.Println(ip + ":" + port.Port())23}

Full Screen

Full Screen

Exec

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 Cmd: []string{"sleep", "1000"},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 ip, err := redis.Host(ctx)16 if err != nil {17 log.Fatal(err)18 }19 port, err := redis.MappedPort(ctx, "6379")20 if err != nil {21 log.Fatal(err)22 }23 fmt.Printf("REDIS URL: %s24 cmd := exec.Command("redis-cli", "-h", ip, "-p", port.Port())25 cmd.Stdin = strings.NewReader("SET key value")26 err = cmd.Run()27 if err != nil {28 log.Fatal(err)29 }30}

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