How to use Stop method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.Stop

commons_integr_test.go

Source:commons_integr_test.go Github

copy

Full Screen

1package database_test2import (3 "context"4 "database/sql"5 "os"6 "testing"7 "github.com/cenkalti/backoff"8 "github.com/docker/go-connections/nat"9 "github.com/stretchr/testify/require"10 "github.com/testcontainers/testcontainers-go"11 "github.com/testcontainers/testcontainers-go/wait"12 "github.com/bygui86/go-testing/db-example/database"13 "github.com/bygui86/go-testing/db-example/logging"14)15const (16 postgresUser = "postgres"17 postgresPw = "supersecret"18 postgresDb = "postgres"19)20func TestMain(m *testing.M) {21 logErr := logging.InitGlobalLogger()22 if logErr != nil {23 panic(logErr) // Panic and fail24 }25 ctx := context.Background()26 postgres, contErr := startPostgres(ctx)27 if contErr != nil {28 panic(contErr) // Panic and fail since there is not much we can do if the container doesn't start29 }30 logging.Log.Info("PostgreSQL container running")31 defer stopPostgres(postgres, ctx)32 host, port := getHostAndPort(postgres, ctx)33 logging.SugaredLog.Infof("PostgreSQL container exposed as: %s:%s", host, port.Port())34 setEnvVars(host, port)35 os.Exit(36 m.Run(),37 )38}39func startPostgres(ctx context.Context) (testcontainers.Container, error) {40 logging.Log.Info("Start PostgreSQL")41 contReq := testcontainers.ContainerRequest{42 Image: "postgres:13.1-alpine",43 ExposedPorts: []string{"5432/tcp"},44 Env: map[string]string{45 "POSTGRES_PASSWORD": postgresPw,46 // "POSTGRES_HOST_AUTH_METHOD": "trust",47 },48 WaitingFor: wait.ForLog("database system is ready to accept connections"),49 }50 postgres, contErr := testcontainers.GenericContainer(51 ctx,52 testcontainers.GenericContainerRequest{53 ContainerRequest: contReq,54 Started: true,55 },56 )57 return postgres, contErr58}59func getHostAndPort(postgres testcontainers.Container, ctx context.Context) (string, nat.Port) {60 expPorts, expErr := postgres.Ports(ctx)61 if expErr != nil {62 panic(expErr)63 }64 logging.Log.Debug("PostgreSQL exposed ports:")65 for k, v := range expPorts {66 logging.SugaredLog.Debugf("\t %s -> %v", k, v)67 }68 host, hostErr := postgres.Host(ctx)69 if hostErr != nil {70 panic(hostErr) // Panic and fail since there is not much we can do if we cannot figure out the container ip71 }72 port, portErr := postgres.MappedPort(ctx, "5432")73 if portErr != nil {74 panic(portErr) // Panic and fail since there is not much we can do if we cannot figure out the container port75 }76 return host, port77}78func setEnvVars(host string, port nat.Port) {79 envErr := os.Setenv("DB_HOST", host)80 if envErr != nil {81 panic(envErr) // Panic and fail since there is not much we can do if we cannot set environment variables82 }83 envErr = os.Setenv("DB_PORT", port.Port())84 if envErr != nil {85 panic(envErr) // Panic and fail since there is not much we can do if we cannot set environment variables86 }87 envErr = os.Setenv("DB_USERNAME", postgresUser)88 if envErr != nil {89 panic(envErr) // Panic and fail since there is not much we can do if we cannot set environment variables90 }91 envErr = os.Setenv("DB_PASSWORD", postgresPw)92 // envErr = os.Setenv("DB_PASSWORD", "")93 if envErr != nil {94 panic(envErr) // Panic and fail since there is not much we can do if we cannot set environment variables95 }96 envErr = os.Setenv("DB_NAME", postgresDb)97 if envErr != nil {98 panic(envErr) // Panic and fail since there is not much we can do if we cannot set environment variables99 }100}101func ping(db *sql.DB) error {102 // WARN: connection takes a bit time to be opened, golang application is so fast that the first ping could easily fail103 pingErr := backoff.Retry(104 func() error {105 err := db.Ping()106 if err != nil {107 logging.Log.Debug("PostgreSQL connection not ready, backing off...")108 return err109 }110 logging.Log.Debug("PostgreSQL connection ready")111 return nil112 },113 backoff.WithMaxRetries(backoff.NewExponentialBackOff(), 10),114 )115 return pingErr116}117func stopPostgres(postgres testcontainers.Container, ctx context.Context) {118 logging.Log.Info("PostgreSQL container stop")119 err := postgres.Terminate(ctx)120 if err != nil {121 logging.SugaredLog.Error("PostgreSQL container stop failed: %s", err.Error())122 }123}124func initConnAndTable(t *testing.T) *sql.DB {125 db, dbErr := database.New()126 require.NoError(t, dbErr)127 pingErr := ping(db)128 require.NoError(t, pingErr)129 initErr := database.InitDb(db)130 require.NoError(t, initErr)131 return db132}...

Full Screen

Full Screen

handlers_integr_test.go

Source:handlers_integr_test.go Github

copy

Full Screen

1// +build integration2package rest_test3import (4 "context"5 "fmt"6 "net/http"7 "net/url"8 "os"9 "testing"10 "time"11 "github.com/docker/go-connections/nat"12 "github.com/stretchr/testify/assert"13 "github.com/stretchr/testify/require"14 "github.com/testcontainers/testcontainers-go"15 "github.com/testcontainers/testcontainers-go/wait"16 "github.com/bygui86/go-testing/rest-examples/http-client/logging"17 "github.com/bygui86/go-testing/rest-examples/http-client/rest"18)19const (20 headerAccept = "Accept"21 headerApplicationJson = "application/json"22)23func TestMain(m *testing.M) {24 logErr := logging.InitGlobalLogger()25 if logErr != nil {26 panic(logErr) // Panic and fail27 }28 ctx := context.Background()29 postgres, contErr := startHttpServer(ctx)30 if contErr != nil {31 panic(contErr) // Panic and fail since there is not much we can do if the container doesn't start32 }33 logging.Log.Info("HTTP server container running")34 defer stopHttpServer(postgres, ctx)35 host, port := getHostAndPort(postgres, ctx)36 logging.SugaredLog.Infof("HTTP server container exposed as: %s:%s", host, port.Port())37 setEnvVars(host, port)38 os.Exit(39 m.Run(),40 )41}42func startHttpServer(ctx context.Context) (testcontainers.Container, error) {43 logging.Log.Info("Start HTTP server")44 contReq := testcontainers.ContainerRequest{45 Image: "bygui86/http-server:v1.0.0",46 ExposedPorts: []string{"8080/tcp"},47 Env: map[string]string{48 "JAEGER_SERVICE_NAME": "http-server",49 },50 WaitingFor: wait.ForLog("http-server up and running"),51 }52 httpServer, contErr := testcontainers.GenericContainer(53 ctx,54 testcontainers.GenericContainerRequest{55 ContainerRequest: contReq,56 Started: true,57 },58 )59 return httpServer, contErr60}61func getHostAndPort(httpServer testcontainers.Container, ctx context.Context) (string, nat.Port) {62 expPorts, expErr := httpServer.Ports(ctx)63 if expErr != nil {64 panic(expErr)65 }66 logging.Log.Debug("HTTP server exposed ports:")67 for k, v := range expPorts {68 logging.SugaredLog.Debugf("\t %s -> %v", k, v)69 }70 host, hostErr := httpServer.Host(ctx)71 if hostErr != nil {72 panic(hostErr) // Panic and fail since there is not much we can do if we cannot figure out the container ip73 }74 port, portErr := httpServer.MappedPort(ctx, "8080")75 if portErr != nil {76 panic(portErr) // Panic and fail since there is not much we can do if we cannot figure out the container port77 }78 return host, port79}80func setEnvVars(host string, port nat.Port) {81 envErr := os.Setenv("REST_SERVER_HOST", host)82 if envErr != nil {83 panic(envErr) // Panic and fail since there is not much we can do if we cannot set environment variables84 }85 envErr = os.Setenv("REST_SERVER_PORT", port.Port())86 if envErr != nil {87 panic(envErr) // Panic and fail since there is not much we can do if we cannot set environment variables88 }89}90func stopHttpServer(httpServer testcontainers.Container, ctx context.Context) {91 logging.Log.Info("HTTP server container stop")92 err := httpServer.Terminate(ctx)93 if err != nil {94 logging.SugaredLog.Error("HTTP server container stop failed: %s", err.Error())95 }96}97func TestGetProducts_Integr(t *testing.T) {98 cfg := rest.LoadConfig()99 serverUrl, serverUrlErr := rest.CreateBaseUrl(cfg.RestServerHost, cfg.RestServerPort)100 require.NoError(t, serverUrlErr)101 serverClient := rest.CreateRestClient()102 server, newErr := rest.New(cfg, serverUrl, serverClient)103 require.NoError(t, newErr)104 startErr := server.Start()105 assert.NoError(t, startErr)106 assert.True(t, server.Running())107 url, urlErr := url.Parse(fmt.Sprintf("http://%s:%d/products", cfg.RestHost, cfg.RestPort))108 require.NoError(t, urlErr)109 request, reqErr := http.NewRequest(http.MethodGet, url.String(), nil)110 require.NoError(t, reqErr)111 request.Header.Set(headerAccept, headerApplicationJson)112 restClient := &http.Client{113 Timeout: 3 * time.Second,114 }115 response, respErr := restClient.Do(request)116 assert.NoError(t, respErr)117 assert.Equal(t, http.StatusOK, response.StatusCode)118 server.Shutdown(1)119}120// TODO getProduct121// TODO createProduct122// TODO updateProduct123// TODO deleteProduct...

Full Screen

Full Screen

log.go

Source:log.go Github

copy

Full Screen

...12// Accept ...13func (logger *LogCollector) Accept(l testcontainers.Log) {14 logger.LogChan <- l15}16// Stop ...17func (logger *LogCollector) Stop() {18 logger.container.StopLogProducer()19 close(logger.LogChan)20}21// LogToStdout ...22func (logger *LogCollector) LogToStdout() {23 for {24 message, ok := <-logger.LogChan25 if !ok {26 return27 }28 log.Print(string(message.Content))29 }30}31// StartLogger ...32func StartLogger(ctx context.Context, c testcontainers.Container) (LogCollector, error) {...

Full Screen

Full Screen

Stop

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 Cmd: []string{"echo", "hello world"},7 WaitingFor: wait.ForLog("hello world"),8 }9 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 log.Fatal(err)13 }14 err = container.Stop(ctx)15 if err != nil {16 log.Fatal(err)17 }18 err = container.Terminate(ctx)19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println("Done")23}24import (25func main() {26 ctx := context.Background()27 req := testcontainers.ContainerRequest{28 ExposedPorts: []string{"80/tcp"},29 Cmd: []string{"echo", "hello world"},30 WaitingFor: wait.ForLog("hello world"),31 }32 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{33 })34 if err != nil {

Full Screen

Full Screen

Stop

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"4444/tcp"},6 WaitingFor: wait.ForListeningPort("4444/tcp"),7 }8 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatalf("Could not start container: %v", err)12 }13 defer container.Terminate(ctx)14 err = container.Stop(ctx)15 if err != nil {16 log.Fatalf("Could not stop container: %v", err)17 }18 time.Sleep(5 * time.Second)19}20import (21func main() {22 ctx := context.Background()23 req := testcontainers.ContainerRequest{24 ExposedPorts: []string{"4444/tcp"},25 WaitingFor: wait.ForListeningPort("4444/tcp"),26 }27 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{28 })29 if err != nil {30 log.Fatalf("Could not start container: %v", err)31 }32 defer container.Terminate(ctx)33 err = container.Stop(ctx)34 if err != nil {35 log.Fatalf("Could not stop container: %v", err)36 }37 time.Sleep(5 * time.Second)38}

Full Screen

Full Screen

Stop

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 }8 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 err = c.Terminate(ctx)14 if err != nil {15 log.Fatal(err)16 }17 ip, err := c.Host(ctx)18 if err != nil {19 log.Fatal(err)20 }21 port, err := c.MappedPort(ctx, "80")22 if err != nil {23 log.Fatal(err)24 }25 fmt.Println("Container IP:", ip)26 fmt.Println("Container port:", port.Int())27 time.Sleep(5 * time.Second)28}

Full Screen

Full Screen

Stop

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 fmt.Printf("postgres is listening on %s:%s23", ip, port.Port())24 err = postgres.Stop(ctx)25 if err != nil {26 log.Fatal(err)27 }28 fmt.Println("postgres is stopped")29}30import (31func main() {32 ctx := context.Background()33 req := testcontainers.ContainerRequest{34 ExposedPorts: []string{"5432/tcp"},35 WaitingFor: wait.ForLog("database system is ready to accept connections"),36 }37 postgres, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{38 })39 if err != nil {40 log.Fatal(err)41 }42 defer postgres.Terminate(ctx)43 ip, err := postgres.Host(ctx)44 if err != nil {45 log.Fatal(err)46 }47 port, err := postgres.MappedPort(ctx, "5432")48 if err != nil {49 log.Fatal(err)50 }

Full Screen

Full Screen

Stop

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: testcontainers.WaitingForLog("hello world"),8 }9 alpine, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 log.Fatal(err)13 }14 err = alpine.Terminate(ctx)15 if err != nil {16 log.Fatal(err)17 }18 fmt.Println("Container stopped")19}20import (21func main() {22 ctx := context.Background()23 req := testcontainers.ContainerRequest{24 Cmd: []string{"echo", "hello world"},25 ExposedPorts: []string{"80/tcp"},26 WaitingFor: testcontainers.WaitingForLog("hello world"),27 }28 alpine, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{29 })30 if err != nil {31 log.Fatal(err)32 }33 err = alpine.Kill(ctx, "SIGKILL")34 if err != nil {35 log.Fatal(err)36 }37 fmt.Println("Container killed")38}39import (40func main() {41 ctx := context.Background()42 req := testcontainers.ContainerRequest{43 Cmd: []string{"echo", "hello world"},44 ExposedPorts: []string{"80/tcp"},

Full Screen

Full Screen

Stop

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)4 defer cancel()5 req := testcontainers.ContainerRequest{6 ExposedPorts: []string{"3306/tcp"},7 WaitingFor: wait.ForLog("port: 3306 MySQL Community Server - GPL"),8 }9 mysql, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 log.Fatal(err)13 }14 err = mysql.Terminate(ctx)15 if err != nil {16 log.Fatal(err)17 }18 fmt.Println("Container stopped")19}

Full Screen

Full Screen

Stop

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 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer postgresContainer.Terminate(ctx)14 port, err := postgresContainer.MappedPort(ctx, "5432")15 if err != nil {16 panic(err)17 }18 fmt.Println(port.Int())19 host, err := postgresContainer.Host(ctx)20 if err != nil {21 panic(err)22 }23 fmt.Println(host)24 containerID, err := postgresContainer.ContainerID(ctx)25 if err != nil {26 panic(err)27 }28 fmt.Println(containerID)29 containerName, err := postgresContainer.ContainerName(ctx)30 if err != nil {31 panic(err)32 }33 fmt.Println(containerName)34 containerState, err := postgresContainer.ContainerState(ctx)35 if err != nil {36 panic(err)37 }38 fmt.Println(containerState)39 containerImage, err := postgresContainer.Image(ctx)40 if err != nil {41 panic(err)42 }43 fmt.Println(containerImage)44 containerIP, err := postgresContainer.ContainerIP(ctx)45 if err != nil {46 panic(err)47 }48 fmt.Println(containerIP)49 networkID, err := postgresContainer.NetworkID(ctx)50 if err != nil {51 panic(err)52 }53 fmt.Println(networkID)54 networkName, err := postgresContainer.NetworkName(ctx)55 if err != nil {56 panic(err)57 }58 fmt.Println(networkName)59 networkGateway, err := postgresContainer.NetworkGateway(ctx)

Full Screen

Full Screen

Stop

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 go func() {14 time.Sleep(5 * time.Second)15 if err := postgres.Terminate(ctx); err != nil {16 log.Fatal(err)17 }18 }()19 ip, err := postgres.Host(ctx)20 if err != nil {21 log.Fatal(err)22 }23 port, err := postgres.MappedPort(ctx, "5432")24 if err != nil {25 log.Fatal(err)26 }27 fmt.Printf("PostgreSQL is available on %s:%s", ip, port.Port())28}

Full Screen

Full Screen

Stop

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(err)12 }13 defer redisContainer.Terminate(ctx)14 ip, err := redisContainer.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := redisContainer.MappedPort(ctx, "6379/tcp")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println(ip, port.Int())23 redisContainer.Terminate(ctx)24 time.Sleep(5 * time.Second)25}

Full Screen

Full Screen

Stop

Using AI Code Generation

copy

Full Screen

1ip, err := testcontainers.GetContainerIP(containerID)2port, err := testcontainers.GetContainerPort(containerID)3ip, err := testcontainers.GetContainerIP(containerID)4port, err := testcontainers.GetContainerPort(containerID)5ip, err := testcontainers.GetContainerIP(containerID)6port, err := testcontainers.GetContainerPort(containerID)7ip, err := testcontainers.GetContainerIP(containerID)8port, err := testcontainers.GetContainerPort(containerID)9ip, err := testcontainers.GetContainerIP(containerID)10port, err := testcontainers.GetContainerPort(containerID)11ip, err := testcontainers.GetContainerIP(containerID)12port, err := testcontainers.GetContainerPort(containerID)

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