How to use Terminate method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.Terminate

container_test.go

Source:container_test.go Github

copy

Full Screen

...32 Image: "alpine",33 })34 require.NotNil(t, c)35 assert.NoError(t, err)36 defer c.Terminate(context.Background()) // nolint: errcheck37}38func TestStartGenericContainer_SuccessButCallbackError(t *testing.T) {39 t.Parallel()40 c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{41 Name: randomString(8),42 Image: "alpine",43 }, testcontainers.WithCallback(func(context.Context, testcontainers.Container, testcontainers.ContainerRequest) error {44 return errors.New("callback error")45 }))46 require.NotNil(t, c)47 defer c.Terminate(context.Background()) // nolint: errcheck48 expected := errors.New("callback error")49 assert.Equal(t, expected, err)50}51func TestStartGenericContainer_NamePrefix(t *testing.T) {52 t.Parallel()53 prefix := randomString(8)54 c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{55 Name: "test",56 Image: "alpine",57 }, testcontainers.WithNamePrefix(prefix))58 require.NotNil(t, c)59 assert.NoError(t, err)60 defer c.Terminate(context.Background()) // nolint: errcheck61 actual, err := c.Name(context.Background())62 expected := fmt.Sprintf("/%s_test", prefix)63 assert.Equal(t, expected, actual)64 assert.NoError(t, err)65}66func TestStartGenericContainer_NameSuffix(t *testing.T) {67 t.Parallel()68 suffix := randomString(8)69 c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{70 Name: "test",71 Image: "alpine",72 }, testcontainers.WithNameSuffix(suffix))73 require.NotNil(t, c)74 assert.NoError(t, err)75 defer c.Terminate(context.Background()) // nolint: errcheck76 actual, err := c.Name(context.Background())77 expected := fmt.Sprintf("/test_%s", suffix)78 assert.Equal(t, expected, actual)79 assert.NoError(t, err)80}81func TestStartGenericContainer_NamePrefixAndSuffix(t *testing.T) {82 t.Parallel()83 prefix := randomString(8)84 suffix := randomString(8)85 c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{86 Name: "test",87 Image: "alpine",88 }, testcontainers.WithNamePrefix(prefix), testcontainers.WithNameSuffix(suffix))89 require.NotNil(t, c)90 assert.NoError(t, err)91 defer c.Terminate(context.Background()) // nolint: errcheck92 actual, err := c.Name(context.Background())93 expected := fmt.Sprintf("/%s_test_%s", prefix, suffix)94 assert.Equal(t, expected, actual)95 assert.NoError(t, err)96}97func TestStartGenericContainer_WithImageName(t *testing.T) {98 t.Parallel()99 c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{100 Name: randomString(8),101 Image: "alpine-unknown",102 }, testcontainers.WithImageName("alpine"))103 require.NotNil(t, c)104 assert.NoError(t, err)105 defer c.Terminate(context.Background()) // nolint: errcheck106}107func TestStartGenericContainer_WithImageTag(t *testing.T) {108 t.Parallel()109 c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{110 Name: randomString(8),111 Image: "alpine:unknown",112 }, testcontainers.WithImageTag("latest"))113 require.NotNil(t, c)114 assert.NoError(t, err)115 defer c.Terminate(context.Background()) // nolint: errcheck116}117func TestStartGenericContainers_Success(t *testing.T) {118 t.Parallel()119 containers, err := testcontainers.StartGenericContainers(context.Background(),120 testcontainers.StartGenericContainerRequest{121 Request: testcontainers.ContainerRequest{122 Name: "postgres",123 Image: "postgres:12-alpine",124 ExposedPorts: []string{":5432"},125 Env: map[string]string{126 "LC_ALL": "C.UTF-8",127 "POSTGRES_DB": "test",128 "POSTGRES_USER": "test",129 "POSTGRES_PASSWORD": "test",130 },131 WaitingFor: wait.ForHealthCheckCmd("pg_isready").132 WithRetries(3).133 WithStartPeriod(time.Second).134 WithTestTimeout(5 * time.Second).135 WithTestInterval(10 * time.Second),136 },137 Options: []testcontainers.GenericContainerOption{138 testcontainers.WithNameSuffix(randomString(8)),139 },140 },141 testcontainers.StartGenericContainerRequest{142 Request: testcontainers.ContainerRequest{143 Name: randomString(8),144 Image: "alpine",145 },146 },147 )148 assert.NoError(t, err)149 require.Len(t, containers, 2)150}151func TestStartGenericContainers_Error(t *testing.T) {152 t.Parallel()153 containers, err := testcontainers.StartGenericContainers(context.Background(),154 testcontainers.StartGenericContainerRequest{155 Request: testcontainers.ContainerRequest{156 Name: randomString(8),157 },158 Options: []testcontainers.GenericContainerOption{159 testcontainers.WithProviderType(-1),160 },161 },162 testcontainers.StartGenericContainerRequest{163 Request: testcontainers.ContainerRequest{164 Name: randomString(8),165 },166 Options: []testcontainers.GenericContainerOption{167 testcontainers.WithProviderType(-1),168 },169 },170 testcontainers.StartGenericContainerRequest{171 Request: testcontainers.ContainerRequest{172 Name: randomString(8),173 Image: "alpine",174 },175 },176 )177 t.Logf("logs:\n%s", err.Error())178 require.NotEmpty(t, containers)179}180func TestStopGenericContainers_Success(t *testing.T) {181 t.Parallel()182 containers, err := testcontainers.StartGenericContainers(context.Background(),183 testcontainers.StartGenericContainerRequest{184 Request: testcontainers.ContainerRequest{185 Name: randomString(8),186 Image: "alpine",187 },188 },189 )190 require.NotEmpty(t, containers)191 require.NoError(t, err)192 err = testcontainers.StopGenericContainers(context.Background(), containers...)193 assert.NoError(t, err)194}195func TestStopGenericContainers_Error(t *testing.T) {196 t.Parallel()197 containers, err := testcontainers.StartGenericContainers(context.Background(),198 testcontainers.StartGenericContainerRequest{199 Request: testcontainers.ContainerRequest{200 Name: randomString(8),201 Image: "alpine",202 },203 },204 )205 require.NotEmpty(t, containers)206 require.NoError(t, err)207 _ = containers[0].Terminate(context.Background()) // nolint: errcheck208 err = testcontainers.StopGenericContainers(context.Background(), containers...)209 require.Error(t, err)210 t.Logf("logs:\n%s", err.Error())211}212// nolint: unparam213func randomString(length int) string {214 var rngSeed int64215 _ = binary.Read(crand.Reader, binary.LittleEndian, &rngSeed) // nolint: errcheck216 r := rand.New(rand.NewSource(rngSeed)) // nolint: gosec217 result := make([]byte, length/2)218 _, _ = r.Read(result)219 return hex.EncodeToString(result)220}...

Full Screen

Full Screen

handler_suite_test.go

Source:handler_suite_test.go Github

copy

Full Screen

...21}22type ContainerAddress struct {23 Host string24 Port string25 Terminate func()26}27var (28 Maria ContainerAddress29 ES ContainerAddress30 Engine *gin.Engine31)32var _ = BeforeSuite(func() {33 fmt.Println("🟢 BeforeSuite Integration test")34 Maria = setupMariaDBContainer()35 ES = setupElasticSearchContainer()36 // init handler37 dbCredential := datastore.DatabaseCredential{38 Host: Maria.Host,39 Port: Maria.Port,40 Username: "root",41 Password: "root",42 Name: "books",43 }44 esURL := fmt.Sprintf("http://%s:%s", ES.Host, ES.Port)45 Engine = handler.InitHandler(dbCredential, esURL)46})47var _ = AfterSuite(func() {48 fmt.Println("⛔️ AfterSuite Integration test")49 Maria.Terminate()50 ES.Terminate()51})52func setupMariaDBContainer() ContainerAddress {53 ctx := context.Background()54 wd, _ := os.Getwd()55 wd += "/../../../seed/init.sql"56 mariaDBContainerReq := testcontainers.ContainerRequest{57 Image: "mariadb:10.5.8",58 ExposedPorts: []string{"3306/tcp"},59 Env: map[string]string{60 "MYSQL_ROOT_USERNAME": "root",61 "MYSQL_ROOT_PASSWORD": "root",62 "MYSQL_DATABASE": "books",63 },64 Mounts: testcontainers.Mounts(testcontainers.BindMount(wd, "/docker-entrypoint-initdb.d/init.sql")),65 WaitingFor: wait.ForLog("3306 mariadb.org binary distribution").WithStartupTimeout(time.Second * 300),66 }67 mariaDBContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{68 ContainerRequest: mariaDBContainerReq,69 Started: true,70 })71 if err != nil {72 log.Fatalf("error starting mariadb container: %s", err)73 }74 mariaDBHost, _ := mariaDBContainer.Host(ctx)75 mariaDBPort, err := mariaDBContainer.MappedPort(ctx, "3306")76 if err != nil {77 log.Fatalf("mariaDBContainer.MappedPort: %s", err)78 }79 terminateContainer := func() {80 logger.Info("terminating maria container...")81 if err := mariaDBContainer.Terminate(ctx); err != nil {82 log.Fatalf("error terminating maria container: %v\n", err)83 }84 }85 return ContainerAddress{mariaDBHost, mariaDBPort.Port(), terminateContainer}86}87func setupElasticSearchContainer() ContainerAddress {88 ctx := context.Background()89 wd, _ := os.Getwd()90 wd += "/../../../seed/es"91 esContainerReq := testcontainers.ContainerRequest{92 Image: "elasticsearch:7.17.6",93 ExposedPorts: []string{"9200/tcp"},94 Env: map[string]string{95 "xpack.security.enabled": "false",96 "discovery.type": "single-node",97 },98 Mounts: testcontainers.Mounts(testcontainers.BindMount(wd, "/pre-test-script")),99 WaitingFor: wait.ForLog("started").WithStartupTimeout(time.Second * 300),100 }101 esContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{102 ContainerRequest: esContainerReq,103 Started: true,104 })105 if err != nil {106 logger.Fatalf("error starting es container: %s", err)107 }108 _, err = esContainer.Exec(ctx, []string{"sh", "/pre-test-script/es_container_db.sh"})109 if err != nil {110 logger.Fatalf("esContainer.Exec: %s", err)111 }112 esHost, _ := esContainer.Host(ctx)113 esPort, err := esContainer.MappedPort(ctx, "9200")114 if err != nil {115 logger.Fatalf("esContainer.MappedPort: %s", err)116 }117 terminateContainer := func() {118 logger.Info("terminating es container...")119 if err := esContainer.Terminate(ctx); err != nil {120 logger.Fatalf("error terminating es container: %v\n", err)121 }122 }123 return ContainerAddress{esHost, esPort.Port(), terminateContainer}124}...

Full Screen

Full Screen

database.go

Source:database.go Github

copy

Full Screen

...62 }63 // Get the host64 host, err := container.Host(ctx)65 if err != nil {66 container.Terminate(ctx)67 return nil, nil, err68 }69 // Get the port70 port, err := container.MappedPort(ctx, "5432")71 if err != nil {72 container.Terminate(ctx)73 return nil, nil, err74 }75 // Create connection string to the test container76 dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",77 host,78 port.Port(),79 "postgres",80 "postgres",81 "postgres")82 // Connect to the database83 database, err := InitDatabase(dsn)84 if err != nil {85 container.Terminate(ctx)86 return nil, nil, err87 }88 return container, database, nil89}90// SetupTestDatabase setups the global DB variable.91func SetupTestDatabase(t *testing.T, ctx context.Context) testcontainers.Container {92 container, database, err := InitTestDatabase(ctx)93 if err != nil {94 t.Fatal(err)95 }96 DB = database97 return container98}...

Full Screen

Full Screen

Terminate

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 port 80"),7 }8 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 ip, err := c.Host(ctx)14 if err != nil {15 log.Fatal(err)16 }17 port, err := c.MappedPort(ctx, "80")18 if err != nil {19 log.Fatal(err)20 }21 fmt.Printf("Container %s is listening on %s:%s", c.GetContainerID(), ip, port.Port())22 err = c.Terminate(ctx)23 if err != nil {24 log.Fatal(err)25 }26}

Full Screen

Full Screen

Terminate

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 port 80"),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, "80")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Printf("Container is listening on %s:%s", ip, port.Port())23}

Full Screen

Full Screen

Terminate

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"5432/tcp"},6 Env: map[string]string{7 },8 WaitingFor: wait.ForLog("database system is ready to accept connections"),9 }10 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{11 })12 if err != nil {13 log.Fatalf("Could not start container: %v", err)14 }15 postgresContainer.Terminate(ctx)16 _, err = postgresContainer.WaitUntilStopped(ctx, 10*time.Second)17 if err != nil {18 log.Fatalf("Could not terminate container: %v", err)19 }20 err = postgresContainer.Terminate(ctx)21 if err != nil {22 log.Fatalf("Could not remove container: %v", err)23 }24 fmt.Println("Done")25}

Full Screen

Full Screen

Terminate

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 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13}14import (15func main() {16 ctx := context.Background()17 req := testcontainers.ContainerRequest{18 ExposedPorts: []string{"6379/tcp"},19 WaitingFor: wait.ForListeningPort("6379/tcp"),20 }21 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{22 })23 if err != nil {24 log.Fatal(err)25 }26}

Full Screen

Full Screen

Terminate

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 }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}

Full Screen

Full Screen

Terminate

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

Full Screen

Full Screen

Terminate

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"8080/tcp"},5 Cmd: []string{"tail", "-f", "/dev/null"},6 WaitingFor: wait.ForListeningPort("8080/tcp"),7 }8 ctx := testcontainers.Context{9 }10 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{11 })12 if err != nil {13 log.Fatal(err)14 }15 err = container.Terminate(ctx)16 if err != nil {17 log.Fatal(err)18 }19 status, err := container.IsRunning(ctx)20 if err != nil {21 log.Fatal(err)22 }23 fmt.Println(status)24}

Full Screen

Full Screen

Terminate

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 mappedPort, err := postgres.MappedPort(ctx, "5432")15 if err != nil {16 panic(err)17 }18 ip, err := postgres.Host(ctx)19 if err != nil {20 panic(err)21 }22 containerID, err := postgres.ContainerID(ctx)23 if err != nil {24 panic(err)25 }26 containerName, err := postgres.ContainerName(ctx)27 if err != nil {28 panic(err)29 }30 containerState, err := postgres.ContainerState(ctx)31 if err != nil {32 panic(err)33 }34 containerImage, err := postgres.Image(ctx)35 if err != nil {36 panic(err)37 }38 containerIPAddress, err := postgres.IPAddress(ctx)39 if err != nil {40 panic(err)41 }42 containerLogs, err := postgres.Logs(ctx)43 if err != nil {44 panic(err)45 }46 containerInfo, err := postgres.Info(ctx)47 if err != nil {48 panic(err)49 }50 containerHostConfig, err := postgres.HostConfig(ctx)51 if err != nil {52 panic(err)53 }54 containerNetworkSettings, err := postgres.NetworkSettings(ctx)55 if err != nil {56 panic(err)57 }58 containerStats, err := postgres.Stats(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