How to use Close method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.Close

testcontainers.go

Source:testcontainers.go Github

copy

Full Screen

...31 oracleUrl := initOracle()32 prestoUrl := initPresto()33 _ = ioutil.WriteFile("config.env", []byte(fmt.Sprintf(`DATABASES=["%s", "%s", "%s"]`, postgresUrl, oracleUrl, prestoUrl)), os.ModePerm)34}35func Close() {36 if postgres != nil {37 _ = postgres.Terminate(context.Background())38 }39 if oracle != nil {40 _ = oracle.Terminate(context.Background())41 }42 if presto != nil {43 _ = presto.Terminate(context.Background())44 }45 if network != nil {46 _ = network.Remove(context.Background())47 }48}49func initPostgres() string {50 ctx := context.Background()51 strPort := "5432/tcp"52 postgresEnv := make(map[string]string)53 postgresEnv["POSTGRES_PASSWORD"] = "postgres"54 postgresEnv["POSTGRES_USER"] = "postgres"55 postgresEnv["POSTGRES_DB"] = "postgres"56 postgres = initContainer("test_postgres", "mdillon/postgis:9.6", strPort, postgresEnv)57 host, err := postgres.Host(ctx)58 utils.FailIfError(err)59 mappedPort, err := postgres.MappedPort(ctx, nat.Port(strPort))60 utils.FailIfError(err)61 url := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", host, mappedPort.Port(), "postgres", "postgres", "postgres")62 db, err := sql.Open("postgres", url)63 utils.FailIfError(err)64 defer utils.CloseSafe(db)65 err = waitForPing(db)66 utils.FailIfError(err)67 return fmt.Sprintf("PostgresDb;poSTgres:postgres/postgres@%s:%s/postgres", host, mappedPort.Port())68}69func initOracle() string {70 ctx := context.Background()71 strPort := "1521/tcp"72 oracle = initContainer("test_oralce", "oracleinanutshell/oracle-xe-11g", "1521/tcp", make(map[string]string))73 host, err := oracle.Host(ctx)74 utils.FailIfError(err)75 mappedPort, err := oracle.MappedPort(ctx, nat.Port(strPort))76 utils.FailIfError(err)77 url := fmt.Sprintf("%s/%s@%s:%s/%s", "system", "oracle", host, mappedPort.Port(), "xe")78 db, err := sql.Open("goracle", url)79 utils.FailIfError(err)80 defer utils.CloseSafe(db)81 err = waitForPing(db)82 utils.FailIfError(err)83 return fmt.Sprintf("OracleDb;Oracle:system/oracle@%s:%s/xe", host, mappedPort.Port())84}85func initPresto() string {86 ctx := context.Background()87 connector := fmt.Sprintf(`connector.name=postgresql88connection-url=jdbc:postgresql://%s:%s/postgres89connection-user=postgres90connection-password=postgres`, "test_postgres", "5432")91 err := ioutil.WriteFile("./presto-image/catalog/postgresql.properties", []byte(connector), os.ModePerm)92 utils.FailIfError(err)93 strPort := "8080/tcp"94 req := testcontainers.ContainerRequest{95 FromDockerfile: testcontainers.FromDockerfile{96 Dockerfile: "Dockerfile",97 Context: "./presto-image",98 },99 ExposedPorts: []string{strPort},100 Networks: []string{networkName},101 WaitingFor: wait.ForLog("======== SERVER STARTED ========"),102 }103 presto, err = testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{104 ContainerRequest: req,105 Started: true,106 })107 utils.FailIfError(err)108 host, err := presto.Host(ctx)109 utils.FailIfError(err)110 mappedPort, err := presto.MappedPort(ctx, nat.Port(strPort))111 utils.FailIfError(err)112 url := fmt.Sprintf("http://user@%s:%s", host, mappedPort.Port())113 db, err := sql.Open("presto", url)114 utils.FailIfError(err)115 defer utils.CloseSafe(db)116 err = waitForPing(db)117 utils.FailIfError(err)118 time.Sleep(3 * time.Second)119 return fmt.Sprintf("PrestoDb;presto:user/password@%s:%s", host, mappedPort.Port())120}121func initContainer(name string, image string, port string, env map[string]string) testcontainers.Container {122 ctx := context.Background()123 req := testcontainers.ContainerRequest{124 Name: name,125 Image: image,126 Env: env,127 ExposedPorts: []string{port},128 Networks: []string{networkName},129 }...

Full Screen

Full Screen

testcontainer.go

Source:testcontainer.go Github

copy

Full Screen

...27 conn, err := Connect(r.ctx, cfg)28 if err != nil {29 return err30 }31 defer func(toClose *DBConnection) {32 cErr := toClose.Close()33 if cErr != nil {34 // report close errors35 if err == nil {36 err = cErr37 } else {38 err = errors.Wrap(err, cErr.Error())39 }40 }41 }(conn)42 r.conn = conn43 runTests(t)44 return err45 })46 if err != nil {47 t.Fatalf("failed to start container %v", err)48 }49}50func (r *DatabaseRunner) Connection() *DBConnection {51 return r.conn52}53func (r *DatabaseRunner) Cleanup(t *testing.T) func() {54 return func() {55 cErr := r.conn.Cleanup()56 if cErr != nil {57 t.Fatalf("failed to cleanup database %v", cErr)58 }59 }60}61func (r *DatabaseRunner) runPostgresContainer(f func(c config.Database) error) error {62 _, file, _, ok := runtime.Caller(0)63 if !ok {64 return fmt.Errorf("failed to get caller")65 }66 dbDirLink := filepath.Join(filepath.Dir(file), "testdata", "db")67 dbDir, err := filepath.EvalSymlinks(dbDirLink)68 if err != nil {69 return err70 }71 username := "tester"72 password := "tester"73 database := "cardmanager"74 // TODO read env variables from config75 req := testcontainers.ContainerRequest{76 Image: "postgres:14-alpine",77 ExposedPorts: []string{"5432/tcp"},78 Mounts: testcontainers.Mounts(79 testcontainers.BindMount(dbDir, "/docker-entrypoint-initdb.d"),80 ),81 Env: map[string]string{82 "POSTGRES_DB": "postgres",83 "POSTGRES_PASSWORD": "test",84 "APP_DB_USER": username,85 "APP_DB_PASS": password,86 "APP_DB_NAME": database,87 },88 AlwaysPullImage: true,89 SkipReaper: true,90 WaitingFor: wait.ForLog("[1] LOG: database system is ready to accept connections"),91 }92 postgresC, err := testcontainers.GenericContainer(r.ctx, testcontainers.GenericContainerRequest{93 ContainerRequest: req,94 Started: true,95 })96 if err != nil {97 return err98 }99 defer func(toClose testcontainers.Container) {100 cErr := toClose.Terminate(r.ctx)101 if cErr != nil {102 // report close errors103 if err == nil {104 err = cErr105 } else {106 err = errors.Wrap(err, cErr.Error())107 }108 }109 }(postgresC)110 if log.Debug().Enabled() {111 logs, err := postgresC.Logs(r.ctx)112 if err != nil {113 return err114 }115 defer logs.Close()116 b, err := io.ReadAll(logs)117 if err != nil {118 return err119 }120 log.Debug().Msg(string(b))121 }122 ip, err := postgresC.Host(r.ctx)123 if err != nil {124 return err125 }126 mappedPort, err := postgresC.MappedPort(r.ctx, "5432")127 if err != nil {128 return err129 }...

Full Screen

Full Screen

mqttdevice_test.go

Source:mqttdevice_test.go Github

copy

Full Screen

...35}36func TestIntegration(t *testing.T) {37 ctx, mqttC, mqttUri := startMqttContainer(t)38 defer mqttC.Terminate(ctx)39 t.Run("ConnectAndClose", func(t *testing.T) {40 t.Logf("Mqtt connection %s ready", mqttUri)41 p := PahoMqttPublisher{Uri: mqttUri, ClientId: "TestMqtt", Username: "guest", Password: "guest"}42 p.Connect()43 p.Close()44 })45 t.Run("Publish", func(t *testing.T) {46 options := mqtt.NewClientOptions().AddBroker(mqttUri)47 options.SetUsername("guest")48 options.SetPassword("guest")49 client := mqtt.NewClient(options)50 token := client.Connect()51 defer client.Disconnect(100)52 token.Wait()53 if token.Error() != nil {54 t.Fatalf("unable to connect to mqtt broker: %v\n", token.Error())55 }56 c := make(chan string)57 defer close(c)58 client.Subscribe("test/publish", 0, func(client mqtt.Client, message mqtt.Message) {59 c <- string(message.Payload())60 }).Wait()61 p := PahoMqttPublisher{Uri: mqttUri, ClientId: "TestMqtt", Username: "guest", Password: "guest"}62 p.Connect()63 defer p.Close()64 p.Publish("test/publish", "Test1234")65 result := <-c66 if result != "Test1234" {67 t.Fatalf("bad message: %v\n", result)68 }69 })70}...

Full Screen

Full Screen

Close

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.ForListeningPort("5432/tcp"),7 }8 postgres, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer postgres.Terminate(ctx)14 port, err := postgres.MappedPort(ctx, "5432/tcp")15 if err != nil {16 panic(err)17 }18 fmt.Println(port.Int())19}20import (21func main() {22 ctx := context.Background()23 req := testcontainers.ContainerRequest{24 ExposedPorts: []string{"5432/tcp"},25 WaitingFor: wait.ForListeningPort("5432/tcp"),26 }27 postgres, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{28 })29 if err != nil {30 panic(err)31 }32 defer postgres.Terminate(ctx)33 err = postgres.Start(ctx)34 if err != nil {35 panic(err)36 }37 port, err := postgres.MappedPort(ctx, "5432/tcp")38 if err != nil {39 panic(err)40 }41 fmt.Println(port.Int())42}43import (44func main() {45 ctx := context.Background()46 req := testcontainers.ContainerRequest{47 ExposedPorts: []string{"5432/tcp"},48 WaitingFor: wait.ForListeningPort("5432/tcp"),49 }50 postgres, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{

Full Screen

Full Screen

Close

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

Full Screen

Full Screen

Close

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.ForLog("port: 3306 MySQL Community Server - GPL"),7 }8 mysqlContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer mysqlContainer.Terminate(ctx)14 ip, err := mysqlContainer.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := mysqlContainer.MappedPort(ctx, "3306")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println(ip, port.Int())23 time.Sleep(30 * time.Second)24}

Full Screen

Full Screen

Close

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.Println(redisHost, redisPort.Int())23}

Full Screen

Full Screen

Close

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.Fatalf("Could not start container: %v", err)12 }13 ip, err := redisContainer.Host(ctx)14 if err != nil {15 log.Fatalf("Could not get container IP: %v", err)16 }17 port, err := redisContainer.MappedPort(ctx, "6379")18 if err != nil {19 log.Fatalf("Could not get container port: %v", err)20 }21 out, err := exec.Command("redis-cli", "-h", ip, "-p", port.Port(), "PING").Output()22 if err != nil {23 log.Fatalf("Could not run Redis command: %v", err)24 }25 fmt.Println(string(out))26 time.Sleep(5 * time.Second)27 redisContainer.Terminate(ctx)28}29import (30func main() {

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1import (2func TestMain(m *testing.M) {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 postgresIP, err := postgres.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 postgresPort, err := postgres.MappedPort(ctx, "5432/tcp")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println(postgresIP)23 fmt.Println(postgresPort.Int())24 os.Exit(m.Run())25}26import (27func TestMain(m *testing.M) {28 fmt.Println("Hello")29}30require (

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"9200/tcp", "9300/tcp"},6 WaitingFor: wait.ForListeningPort("9200/tcp"),7 }8 elasticContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer elasticContainer.Terminate(ctx)14 ip, err := elasticContainer.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := elasticContainer.MappedPort(ctx, "9200/tcp")19 if err != nil {20 panic(err)21 }22 fmt.Printf("Elasticsearch is up and running on %s:%s", ip, port.Port())23}

Full Screen

Full Screen

Close

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 ip, err := redisContainer.Host(ctx)14 if err != nil {15 log.Fatal(err)16 }17 port, err := redisContainer.MappedPort(ctx, "6379")18 if err != nil {19 log.Fatal(err)20 }21 fmt.Printf("Container IP: %s, Port: %s22", ip, port.Port())23 defer redisContainer.Terminate(ctx)24}

Full Screen

Full Screen

Close

Using AI Code Generation

copy

Full Screen

1import (2func TestClose(t *testing.T) {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"3306/tcp"},6 WaitingFor: wait.ForLog("port: 3306 MySQL Community Server - GPL").WithStartupTimeout(60 * time.Second),7 }8 mysql, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer mysql.Terminate(ctx)14 port, err := mysql.MappedPort(ctx, "3306/tcp")15 if err != nil {16 log.Fatal(err)17 }18 fmt.Println(port.Int())19 ip, err := mysql.Host(ctx)20 if err != nil {21 log.Fatal(err)22 }23 fmt.Println(ip)24 mysql.Terminate(ctx)25}26import (27func TestClose(t *testing.T) {28 ctx := context.Background()29 req := testcontainers.ContainerRequest{30 ExposedPorts: []string{"3306/tcp"},31 WaitingFor: wait.ForLog("port: 3306 MySQL Community Server - GPL").WithStartupTimeout(60 * time.Second),32 }33 mysql, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{34 })35 if err != nil {36 log.Fatal(err)37 }38 defer mysql.Terminate(ctx)39 port, err := mysql.MappedPort(ctx, "3306/tcp")40 if err != nil {41 log.Fatal(err)42 }43 fmt.Println(port.Int())44 ip, err := mysql.Host(ctx

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