How to use init method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.init

testcontainers.go

Source:testcontainers.go Github

copy

Full Screen

...20var oracle testcontainers.Container21var presto testcontainers.Container22var network testcontainers.Network23var networkName string24func init() {25 provider, err := testcontainers.NewDockerProvider()26 utils.FailIfError(err)27 networkName = uuid.Generate().String()28 network, err = provider.CreateNetwork(context.Background(), testcontainers.NetworkRequest{Name: networkName})29 utils.FailIfError(err)30 postgresUrl := initPostgres()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 }130 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{131 ContainerRequest: req,132 Started: true,133 })134 utils.FailIfError(err)135 return container...

Full Screen

Full Screen

database.go

Source:database.go Github

copy

Full Screen

...39 db.AutoMigrate(&Token{})40 }41 return db, err42}43// InitTestDatabase initializes a container and a database connection.44func InitTestDatabase(ctx context.Context) (testcontainers.Container, *gorm.DB, error) {45 // Create the Postgres test container46 req := testcontainers.ContainerRequest{47 Image: "postgis/postgis:latest",48 ExposedPorts: []string{"5432/tcp"},49 Env: map[string]string{50 "POSTGRES_DB": "postgres",51 "POSTGRES_USER": "postgres",52 "POSTGRES_PASSWORD": "postgres",53 },54 WaitingFor: wait.ForLog("database system is ready to accept connections").WithOccurrence(2),55 }56 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{57 ContainerRequest: req,...

Full Screen

Full Screen

runDockerByYml.go

Source:runDockerByYml.go Github

copy

Full Screen

...9 "strings"10)11func StartInitContainer(compose DockerCompose, blockChannel chan int) error {12 ctx := context.Background()13 initRequests := testcontainers.ParallelContainerRequest{}14 for _, v := range compose.Services {15 if v.Init == true {16 newService := getRequest(v)17 initRequests = append(initRequests, newService)18 }19 }20 _, err := testcontainers.ParallelContainers(ctx, initRequests, testcontainers.ParallelContainersOptions{})21 if err != nil {22 e, ok := err.(testcontainers.ParallelContainersError)23 if !ok {24 log.Fatalf("unknown error: %v", err)25 }26 for _, pe := range e.Errors {27 fmt.Println(pe.Request, pe.Error)28 }29 return err30 }31 blockChannel <- 66632 return nil33}34func StartDockerByYml(compose DockerCompose) error {...

Full Screen

Full Screen

init

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

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"5432/tcp"},5 WaitingFor: wait.ForLog("database system is ready to accept connections"),6 }7 ctx := context.Background()8 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer postgresContainer.Terminate(ctx)14 ip, err := postgresContainer.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := postgresContainer.MappedPort(ctx, "5432")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Printf("postgres is available at %s:%s23", ip, port.Port())24}

Full Screen

Full Screen

init

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 Env: map[string]string{8 },9 }10 mysqlContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{11 })12 if err != nil {13 log.Fatal(err)14 }15 defer mysqlContainer.Terminate(ctx)16 ip, err := mysqlContainer.Host(ctx)17 if err != nil {18 log.Fatal(err)19 }20 port, err := mysqlContainer.MappedPort(ctx, "3306/tcp")21 if err != nil {22 log.Fatal(err)23 }24 fmt.Println(ip)25 fmt.Println(port.Int())26 time.Sleep(100000 * time.Second)27}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"6379/tcp"},5 WaitingFor: wait.ForListeningPort("6379/tcp"),6 }7 ctx := context.Background()8 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 ip, err := redis.Host(ctx)14 if err != nil {15 log.Fatal(err)16 }17 port, err := redis.MappedPort(ctx, "6379")18 if err != nil {19 log.Fatal(err)20 }21 fmt.Printf("redis is available at %s:%s22", ip, port.Port())23}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func TestMain(m *testing.M) {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.Fatalf("Could not start container: %v", err)12 }13 defer mysqlContainer.Terminate(ctx)14 host, err := mysqlContainer.Host(ctx)15 if err != nil {16 log.Fatalf("Could not get host: %v", err)17 }18 port, err := mysqlContainer.MappedPort(ctx, "3306")19 if err != nil {20 log.Fatalf("Could not get port: %v", err)21 }22 fmt.Printf("host: %s, port: %s", host, port.Port())23 code := m.Run()24 os.Exit(code)25}26import (27func TestMain(m *testing.M) {28 ctx := context.Background()29 req := testcontainers.ContainerRequest{30 ExposedPorts: []string{"3306/tcp"},31 WaitingFor: wait.ForLog("port: 3306 MySQL Community Server - GPL"),32 }33 mysqlContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{34 })35 if err != nil {36 log.Fatalf("Could not start container: %v", err)37 }38 defer mysqlContainer.Terminate(ctx)39 host, err := mysqlContainer.Host(ctx)40 if err != nil {41 log.Fatalf("Could not get host: %v", err)42 }

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4}5import (6func main() {7 fmt.Println("Hello World!")8}9import (10func main() {11 fmt.Println("Hello World!")12}13import (14func main() {15 fmt.Println("Hello World!")16}17import (18func main() {19 fmt.Println("Hello World!")20}

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