How to use ServiceContainer method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.ServiceContainer

main_test.go

Source:main_test.go Github

copy

Full Screen

1//go:build integration2// Copyright 2022 Google LLC3//4// Licensed under the Apache License, Version 2.0 (the "License");5// you may not use this file except in compliance with the License.6// You may obtain a copy of the License at7//8// https://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing, software11// distributed under the License is distributed on an "AS IS" BASIS,12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13// See the License for the specific language governing permissions and14// limitations under the License.15package main16import (17 "bytes"18 "context"19 "encoding/json"20 "github.com/stretchr/testify/assert"21 database "cloud.google.com/go/spanner/admin/database/apiv1"22 instance "cloud.google.com/go/spanner/admin/instance/apiv1"23 "embed"24 "fmt"25 "github.com/cloudspannerecosystem/spanner-gaming-sample/gaming-profile-service/models"26 "github.com/testcontainers/testcontainers-go"27 "github.com/testcontainers/testcontainers-go/wait"28 databasepb "google.golang.org/genproto/googleapis/spanner/admin/database/v1"29 instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1"30 "io/ioutil"31 "log"32 "net/http"33 "os"34 "strings"35 "testing"36)37//go:embed test_data/schema.sql38var SCHEMAFILE embed.FS39var TESTNETWORK = "game-sample-test"40// These integration tests run against the Spanner emulator. The emulator41// must be running and accessible prior to integration tests running.42type Emulator struct {43 testcontainers.Container44 Endpoint string45 Project string46 Instance string47 Database string48}49type Service struct {50 testcontainers.Container51 Endpoint string52}53func teardown(ctx context.Context, emulator *Emulator, service *Service) {54 emulator.Terminate(ctx)55 service.Terminate(ctx)56}57func setupSpannerEmulator(ctx context.Context) (*Emulator, error) {58 req := testcontainers.ContainerRequest{59 Image: "gcr.io/cloud-spanner-emulator/emulator:latest",60 ExposedPorts: []string{"9010/tcp"},61 Networks: []string{62 TESTNETWORK,63 },64 NetworkAliases: map[string][]string{65 TESTNETWORK: []string{66 "emulator",67 },68 },69 Name: "emulator",70 WaitingFor: wait.ForLog("gRPC server listening at"),71 }72 spannerEmulator, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{73 ContainerRequest: req,74 Started: true,75 })76 if err != nil {77 return nil, err78 }79 // Retrieve the container IP80 ip, err := spannerEmulator.Host(ctx)81 if err != nil {82 return nil, err83 }84 // Retrieve the container port85 port, err := spannerEmulator.MappedPort(ctx, "9010")86 if err != nil {87 return nil, err88 }89 // OS environment needed for setting up instance and database90 os.Setenv("SPANNER_EMULATOR_HOST", fmt.Sprintf("%s:%d", ip, port.Int()))91 var ec = Emulator{92 Container: spannerEmulator,93 Endpoint: "emulator:9010",94 Project: "test-project",95 Instance: "test-instance",96 Database: "test-database",97 }98 // Create instance99 err = setupInstance(ctx, ec)100 if err != nil {101 return nil, err102 }103 // Define the database and schema104 err = setupDatabase(ctx, ec)105 if err != nil {106 return nil, err107 }108 return &ec, nil109}110func setupInstance(ctx context.Context, ec Emulator) error {111 instanceAdmin, err := instance.NewInstanceAdminClient(ctx)112 if err != nil {113 log.Fatal(err)114 }115 defer instanceAdmin.Close()116 op, err := instanceAdmin.CreateInstance(ctx, &instancepb.CreateInstanceRequest{117 Parent: fmt.Sprintf("projects/%s", ec.Project),118 InstanceId: ec.Instance,119 Instance: &instancepb.Instance{120 Config: fmt.Sprintf("projects/%s/instanceConfigs/%s", ec.Project, "emulator-config"),121 DisplayName: ec.Instance,122 NodeCount: 1,123 },124 })125 if err != nil {126 return fmt.Errorf("could not create instance %s: %v", fmt.Sprintf("projects/%s/instances/%s", ec.Project, ec.Instance), err)127 }128 // Wait for the instance creation to finish.129 i, err := op.Wait(ctx)130 if err != nil {131 return fmt.Errorf("waiting for instance creation to finish failed: %v", err)132 }133 // The instance may not be ready to serve yet.134 if i.State != instancepb.Instance_READY {135 fmt.Printf("instance state is not READY yet. Got state %v\n", i.State)136 }137 fmt.Printf("Created emulator instance [%s]\n", ec.Instance)138 return nil139}140func setupDatabase(ctx context.Context, ec Emulator) error {141 // get schema statements from file142 schema, _ := SCHEMAFILE.ReadFile("test_data/schema.sql")143 // TODO: remove this when the Spanner Emulator supports 'DEFAULT' syntax144 schemaStringFix := strings.Replace(string(schema), "account_balance NUMERIC NOT NULL DEFAULT (0.00),", "account_balance NUMERIC,", 1)145 schemaStatements := strings.Split(schemaStringFix, ";")146 adminClient, err := database.NewDatabaseAdminClient(ctx)147 if err != nil {148 return err149 }150 defer adminClient.Close()151 op, err := adminClient.CreateDatabase(ctx, &databasepb.CreateDatabaseRequest{152 Parent: fmt.Sprintf("projects/%s/instances/%s", ec.Project, ec.Instance),153 CreateStatement: "CREATE DATABASE `" + ec.Database + "`",154 ExtraStatements: schemaStatements,155 })156 if err != nil {157 fmt.Printf("Error: [%s]", err)158 return err159 }160 if _, err := op.Wait(ctx); err != nil {161 fmt.Printf("Error: [%s]", err)162 return err163 }164 fmt.Printf("Created emulator database [%s]\n", ec.Database)165 return nil166}167func setupService(ctx context.Context, ec *Emulator) (*Service, error) {168 var service = "profile-service"169 req := testcontainers.ContainerRequest{170 Image: fmt.Sprintf("%s:latest", service),171 Name: service,172 ExposedPorts: []string{"80:80/tcp"}, // Bind to 80 on localhost to avoid not knowing about the container port173 Networks: []string{TESTNETWORK},174 NetworkAliases: map[string][]string{175 TESTNETWORK: []string{176 service,177 },178 },179 Env: map[string]string{180 "SPANNER_PROJECT_ID": ec.Project,181 "SPANNER_INSTANCE_ID": ec.Instance,182 "SPANNER_DATABASE_ID": ec.Database,183 "SERVICE_HOST": "0.0.0.0",184 "SERVICE_PORT": "80",185 "SPANNER_EMULATOR_HOST": ec.Endpoint,186 },187 WaitingFor: wait.ForLog("Listening and serving HTTP on 0.0.0.0:80"),188 }189 serviceContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{190 ContainerRequest: req,191 Started: true,192 })193 if err != nil {194 return nil, err195 }196 // Retrieve the container endpoint197 endpoint, err := serviceContainer.Endpoint(ctx, "")198 if err != nil {199 return nil, err200 }201 return &Service{202 Container: serviceContainer,203 Endpoint: endpoint,204 }, nil205}206var playerUUIDs []string207func TestMain(m *testing.M) {208 ctx := context.Background()209 // Setup the docker network so containers can talk to each other210 nr := testcontainers.NetworkRequest{211 Name: TESTNETWORK,212 Attachable: true,213 }214 _, err := testcontainers.GenericNetwork(ctx, testcontainers.GenericNetworkRequest{215 NetworkRequest: nr,216 })217 if err != nil {218 fmt.Printf("Error setting up docker test network: %s\n", err)219 os.Exit(1)220 }221 // Setup the emulator container and default instance/database222 spannerEmulator, err := setupSpannerEmulator(ctx)223 if err != nil {224 fmt.Printf("Error setting up emulator: %s\n", err)225 os.Exit(1)226 }227 // Run service228 service, err := setupService(ctx, spannerEmulator)229 if err != nil {230 fmt.Printf("Error setting up service: %s\n", err)231 os.Exit(1)232 }233 defer teardown(ctx, spannerEmulator, service)234 os.Exit(m.Run())235}236func TestAddPlayers(t *testing.T) {237 type TestPlayer struct {238 Player_name string `json:"player_name"`239 Email string `json:"email"`240 Password string `json:"password"`241 }242 var players = []TestPlayer{243 {244 Email: "test@gmail.com",245 Password: "insecure_password",246 Player_name: "test player",247 },248 }249 for _, p := range players {250 pJson, err := json.Marshal(p)251 assert.Nil(t, err)252 bufferJson := bytes.NewBuffer(pJson)253 // Test adding non-existing players254 response, err := http.Post("http://localhost/players", "application/json", bufferJson)255 assert.Nil(t, err)256 assert.Equal(t, 201, response.StatusCode)257 // Add playerUUID from response to player_slice to be used later258 var data string259 body, err := ioutil.ReadAll(response.Body)260 if err != nil {261 t.Fatal(err.Error())262 }263 json.Unmarshal(body, &data)264 playerUUIDs = append(playerUUIDs, data)265 // Test adding same player, should be statuscode 400 since player exists from previous call266 response, err = http.Post("http://localhost/players", "application/json", bufferJson)267 assert.Nil(t, err)268 assert.Equal(t, 400, response.StatusCode)269 }270}271func TestGetPlayers(t *testing.T) {272 assert.NotNil(t, playerUUIDs)273 // For each added uuid, get that data and validate response code (assuming the result was not empty)274 if len(playerUUIDs) != 0 {275 for _, pUUID := range playerUUIDs {276 response, err := http.Get(fmt.Sprintf("http://localhost/players/%s", pUUID))277 if err != nil {278 t.Fatal(err.Error())279 }280 body, err := ioutil.ReadAll(response.Body)281 if err != nil {282 t.Fatal(err.Error())283 }284 var pData models.Player285 json.Unmarshal(body, &pData)286 assert.NotEmpty(t, pData.PlayerUUID)287 assert.NotEmpty(t, pData.Email)288 assert.NotEmpty(t, pData.Stats)289 }290 }291}...

Full Screen

Full Screen

test_helper.go

Source:test_helper.go Github

copy

Full Screen

1package helper2import (3 "context"4 "fmt"5 "github.com/testcontainers/testcontainers-go"6 "github.com/testcontainers/testcontainers-go/wait"7)8type serviceContainer struct {9 testcontainers.Container10 URI string11}12func SetupService(ctx context.Context) (*serviceContainer, error) {13 req := testcontainers.ContainerRequest{14 AlwaysPullImage: false,15 Image: "gopher-translator-service:1.0",16 AutoRemove: true,17 ExposedPorts: []string{"8080/tcp"},18 WaitingFor: wait.ForHTTP("/v1/health").WithPort("8080"),19 }20 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{21 ContainerRequest: req,22 Started: true,23 })24 if err != nil {25 return nil, err26 }27 ip, err := container.Host(ctx)28 if err != nil {29 return nil, err30 }31 mappedPort, err := container.MappedPort(ctx, "8080")32 if err != nil {33 return nil, err34 }35 uri := fmt.Sprintf("http://%s:%s", ip, mappedPort.Port())36 return &serviceContainer{Container: container, URI: uri}, nil37}...

Full Screen

Full Screen

ServiceContainer

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.Printf("Redis is available at %s:%s23", ip, port.Port())24 time.Sleep(5 * time.Second)25}

Full Screen

Full Screen

ServiceContainer

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")18 if err != nil {19 log.Fatal(err)20 }21 fmt.Printf("Redis is available at %s:%s", ip, port.Port())22}23func main() {24 ctx := context.Background()25 req := testcontainers.ContainerRequest{26 ExposedPorts: []string{"6379/tcp"},27 WaitingFor: wait.ForLog("Ready to accept connections"),28 }29 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{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")40 if err != nil {41 log.Fatal(err)42 }43 fmt.Printf("Redis is available at %s:%s", ip, port.Port())44}45func main() {46 ctx := context.Background()47 req := testcontainers.ContainerRequest{48 ExposedPorts: []string{"6379/tcp"},49 WaitingFor: wait.ForLog("Ready to accept connections"),50 }51 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{52 })53 if err != nil {54 log.Fatal(err)55 }

Full Screen

Full Screen

ServiceContainer

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 nginxContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer nginxContainer.Terminate(ctx)14 ip, err := nginxContainer.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := nginxContainer.MappedPort(ctx, "80")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println("Nginx is available on ", ip, ":", port.Int())23 if err != nil {24 log.Fatal(err)25 }26 defer resp.Body.Close()27 fmt.Println("Response Status:", resp.Status)28 fmt.Println("Response Headers:", resp.Header)29 fmt.Println("Response Body:", resp.Body)30 time.Sleep(time.Second * 5)31}

Full Screen

Full Screen

ServiceContainer

Using AI Code Generation

copy

Full Screen

1func main() {2 ctx := context.Background()3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"27017/tcp"},5 WaitingFor: wait.ForLog("waiting for connections on port"),6 }7 mongoC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{8 })9 if err != nil {10 log.Fatal(err)11 }12 defer mongoC.Terminate(ctx)13 mongoPort, err := mongoC.MappedPort(ctx, "27017/tcp")14 if err != nil {15 log.Fatal(err)16 }17 fmt.Println(mongoPort.Int())18}19func main() {20 ctx := context.Background()21 req := testcontainers.ContainerRequest{22 ExposedPorts: []string{"27017/tcp"},23 WaitingFor: wait.ForLog("waiting for connections on port"),24 }25 mongoC, err := testcontainers.NewContainer(ctx, req)26 if err != nil {27 log.Fatal(err)28 }29 defer mongoC.Terminate(ctx)30 mongoPort, err := mongoC.MappedPort(ctx, "27017/tcp")31 if err != nil {32 log.Fatal(err)33 }34 fmt.Println(mongoPort.Int())35}36github.com/testcontainers/testcontainers-go.(*DockerProvider).NewContainer(0x0, 0x6c4e80, 0xc0000b4018, 0xc0000b4018, 0x0, 0x0, 0x0)

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