How to use Source method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.Source

testcontainers.go

Source:testcontainers.go Github

copy

Full Screen

...34 "MYSql_PASSWORD": dbSqlPassword,35 "MYSql_ROOT_PASSWORD": dbSqlPassword,36 },37 Mounts: testcontainers.ContainerMounts{38 {Source: testcontainers.GenericBindMountSource{HostPath: schema}, Target: "/docker-entrypoint-initdb.d/mysql-schema.sql"},39 {Source: testcontainers.GenericBindMountSource{HostPath: config}, Target: "/etc/mysql/conf.d/my.cnf"},40 },41 WaitingFor: wait.ForLog("port: 3306 MySql Community Server - GPL"),42 SkipReaper: true,43 }44 mySqlC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{45 ContainerRequest: req,46 Started: true,47 })48 if !errors.Is(err, nil) {49 return nil, errors.Wrap(err, 1)50 }51 return mySqlC, nil52}53func SetupSqlHandlerMySql(ctx context.Context) (database.SqlHandler, testcontainers.Container, error) {54 mySqlC, err := SetupMySql(ctx)55 if !errors.Is(err, nil) {56 return nil, nil, errors.Wrap(err, 1)57 }58 host, _ := mySqlC.Host(ctx)59 p, _ := mySqlC.MappedPort(ctx, nat.Port("3306/tcp"))60 port := strconv.Itoa(p.Int())61 connectionString := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", dbSqlUsername, dbSqlPassword, host, port, dbSqlName)62 mySqlDb, err := sql_handler.NewSqlDatabase("mysql", connectionString)63 if !errors.Is(err, nil) {64 mySqlC.Terminate(ctx)65 return nil, nil, errors.Wrap(err, 1)66 }67 return mySqlDb, mySqlC, nil68}69func SetupPostgres(ctx context.Context) (testcontainers.Container, error) {70 seedDataPath, err := os.Getwd()71 if !errors.Is(err, nil) {72 return nil, errors.Wrap(err, 1)73 }74 schema := seedDataPath + "/db-data/postgres-schema.sql"75 req := testcontainers.ContainerRequest{76 Image: "postgres:latest",77 ExposedPorts: []string{"5432/tcp"},78 Env: map[string]string{79 "POSTGRES_DB": dbSqlName,80 "POSTGRES_USER": dbSqlUsername,81 "POSTGRES_PASSWORD": dbSqlPassword,82 },83 Mounts: testcontainers.ContainerMounts{84 {Source: testcontainers.GenericBindMountSource{HostPath: schema}, Target: "/docker-entrypoint-initdb.d/postgres-schema.sql"},85 },86 WaitingFor: wait.ForLog("database system is ready to accept connections"),87 SkipReaper: true,88 }89 postgresC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{90 ContainerRequest: req,91 Started: true,92 })93 if !errors.Is(err, nil) {94 return nil, errors.Wrap(err, 1)95 }96 return postgresC, nil97}98func SetupSqlHandlerPostgres(ctx context.Context) (database.SqlHandler, testcontainers.Container, error) {...

Full Screen

Full Screen

testcontainer.go

Source:testcontainer.go Github

copy

Full Screen

...15 // all Strategies should have a startupTimeout to avoid waiting infinitely16 startupTimeout time.Duration17 // additional properties18 driverName string19 dataSourceName string20 port nat.Port21 PollInterval time.Duration22}23// ForDb constructs a HTTP strategy waiting on port 80 and status code 20024func ForDb(driverName string, dataSourceName string, port string) *DbStrategy {25 return &DbStrategy{26 startupTimeout: 60 * time.Second,27 driverName: driverName,28 dataSourceName: dataSourceName,29 port: nat.Port(port),30 PollInterval: 500 * time.Millisecond,31 }32}33// fluent builders for each property34// since go has neither covariance nor generics, the return type must be the type of the concrete implementation35// this is true for all properties, even the "shared" ones like startupTimeout36// WithStartupTimeout can be used to change the default startup timeout37func (ws *DbStrategy) WithStartupTimeout(startupTimeout time.Duration) *DbStrategy {38 ws.startupTimeout = startupTimeout39 return ws40}41// WithPollInterval can be used to override the default polling interval of 100 milliseconds42func (ws *DbStrategy) WithPollInterval(pollInterval time.Duration) *DbStrategy {43 ws.PollInterval = pollInterval44 return ws45}46// WaitUntilReady implements Strategy.WaitUntilReady47func (ws *DbStrategy) WaitUntilReady(ctx context.Context, target wait.StrategyTarget) (err error) {48 // limit context to startupTimeout49 ctx, cancelContext := context.WithTimeout(ctx, ws.startupTimeout)50 defer cancelContext()51 if !strings.Contains(ws.dataSourceName, "<port>") {52 return faults.Errorf("missing placeholder <port> in %s", ws.dataSourceName)53 }54 var ds string55 for {56 select {57 case <-ctx.Done():58 return ctx.Err()59 default:60 var err error61 if ds == "" {62 var port nat.Port63 port, err = target.MappedPort(ctx, ws.port)64 if err == nil {65 ds = strings.ReplaceAll(ws.dataSourceName, "<port>", port.Port())66 }67 }68 if err == nil {69 _, err = Connect(ws.driverName, ds)70 }71 if err != nil {72 time.Sleep(ws.PollInterval)73 continue74 }75 return nil76 }77 }78}79func Container(80 image string,81 exPort string,82 env map[string]string,83 driverName string,84 dataSourceName string,85 timeout int,86) (context.Context, testcontainers.Container, nat.Port, error) {87 ctx := context.Background()88 req := testcontainers.ContainerRequest{89 Image: image,90 ExposedPorts: []string{exPort},91 Env: env,92 WaitingFor: ForDb(93 driverName,94 dataSourceName,95 exPort,96 ).WithStartupTimeout(time.Duration(timeout) * time.Minute),97 }98 server, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{99 ContainerRequest: req,100 Started: true,101 })102 var port nat.Port103 if err == nil {104 port, err = server.MappedPort(ctx, nat.Port(exPort))105 }106 return ctx, server, port, faults.Wrap(err)107}...

Full Screen

Full Screen

database.go

Source:database.go Github

copy

Full Screen

1package models2import (3 "context"4 "fmt"5 "github.com/testcontainers/testcontainers-go"6 "github.com/testcontainers/testcontainers-go/wait"7 "gorm.io/driver/postgres"8 "gorm.io/gorm"9 "os"10 "testing"11)12// DB is a global variable for the gorm database.13var DB *gorm.DB14// ConnectDatabaseEnv connects to the database using environment variables.15func ConnectDatabaseEnv() {16 dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",17 os.Getenv("DB_HOST"),18 os.Getenv("DB_PORT"),19 os.Getenv("DB_USER"),20 os.Getenv("DB_PASS"),21 os.Getenv("DB_NAME"))22 ConnectDatabase(dsn)23}24// ConnectDatabase connects to the database using a data source name25func ConnectDatabase(dsn string) {26 db, err := InitDatabase(dsn)27 if err != nil {28 panic(err)29 }30 DB = db31}32// InitDatabase opens and migrates the database using a data source name33func InitDatabase(dsn string) (*gorm.DB, error) {34 db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})35 // Migrate the db36 if err == nil {37 db.AutoMigrate(&Account{})38 db.AutoMigrate(&Resource{})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,58 Started: true,59 })60 if err != nil {61 panic(err)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

Source

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"27017/tcp"},6 WaitingFor: wait.ForListeningPort("27017/tcp"),7 }8 mongoContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 ip, err := mongoContainer.Host(ctx)14 if err != nil {15 panic(err)16 }17 port, err := mongoContainer.MappedPort(ctx, "27017")18 if err != nil {19 panic(err)20 }21 fmt.Println("MongoDB started on " + ip + ":" + port.Port())22 err = mongoContainer.Terminate(ctx)23 if err != nil {24 panic(err)25 }26}

Full Screen

Full Screen

Source

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 }

Full Screen

Full Screen

Source

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: wait.ForLog("hello world"),8 }9 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 log.Fatal(err)13 }14 id, err := c.ContainerID(ctx)15 if err != nil {16 log.Fatal(err)17 }18 fmt.Println(id)19 ip, err := c.Host(ctx)20 if err != nil {21 log.Fatal(err)22 }23 fmt.Println(ip)24 port, err := c.MappedPort(ctx, "80")25 if err != nil {26 log.Fatal(err)27 }28 fmt.Println(port.Int())29 logs, err := c.Logs(ctx)30 if err != nil {31 log.Fatal(err)32 }33 defer logs.Close()34 _, err = io.Copy(os.Stdout, logs)35 if err != nil {36 log.Fatal(err)37 }38 err = c.Terminate(ctx)39 if err != nil {40 log.Fatal(err)41 }42}43import (44func main() {45 ctx := context.Background()46 req := testcontainers.ContainerRequest{47 Cmd: []string{"echo", "hello world"},48 ExposedPorts: []string{"80/tcp"},49 WaitingFor: wait.ForLog("hello world"),50 }51 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{52 })

Full Screen

Full Screen

Source

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 Cmd: []string{"sh", "-c", "while true; do echo hello world; sleep 1; done"},6 ExposedPorts: []string{"80/tcp"},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 defer container.Terminate(ctx)15 ip, err := container.Host(ctx)16 if err != nil {17 log.Fatal(err)18 }19 port, err := container.MappedPort(ctx, "80")20 if err != nil {21 log.Fatal(err)22 }23 fmt.Printf("Container IP: %s, mapped port: %s", ip, port.Port())24 file, err := os.Create("hello-world.txt")25 if err != nil {26 log.Fatal(err)27 }28 defer file.Close()29 err = container.CopyToContainer(ctx, "/hello-world.txt", file)30 if err != nil {31 log.Fatal(err)32 }33 file, err = os.Open("hello-world.txt")34 if err != nil {35 log.Fatal(err)36 }37 defer file.Close()38 err = container.CopyFromContainer(ctx, "/hello-world.txt", file)39 if err != nil {40 log.Fatal(err)41 }42 out, err := container.Exec(ctx, []string{"cat", "/hello-world.txt"})43 if err != nil {44 log.Fatal(err)45 }46 io.Copy(os.Stdout, out)

Full Screen

Full Screen

Source

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("URL: ", url)23 resp, err := http.Get(url)24 if err != nil {25 log.Fatal(err)26 }27 defer resp.Body.Close()28 body, err := ioutil.ReadAll(resp.Body)29 if err != nil {30 log.Fatal(err)31 }32 fmt.Println("Body: ", string(body))33 time.Sleep(10 * time.Second)34}

Full Screen

Full Screen

Source

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 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 port, err := mysqlContainer.MappedPort(ctx, "3306")16 if err != nil {17 log.Fatal(err)18 }19 ip, err := mysqlContainer.Host(ctx)20 if err != nil {21 log.Fatal(err)22 }23 containerName, err := mysqlContainer.Name(ctx)24 if err != nil {25 log.Fatal(err)26 }27 containerID, err := mysqlContainer.ContainerID(ctx)28 if err != nil {29 log.Fatal(err)30 }31 containerHostname, err := mysqlContainer.Hostname(ctx)32 if err != nil {33 log.Fatal(err)34 }35 containerImage, err := mysqlContainer.Image(ctx)36 if err != nil {37 log.Fatal(err)38 }39 containerState, err := mysqlContainer.State(ctx)40 if err != nil {41 log.Fatal(err)42 }43 containerCommand, err := mysqlContainer.Command(ctx)44 if err != nil {45 log.Fatal(err)46 }47 containerCreatedAt, err := mysqlContainer.CreatedAt(ctx)48 if err != nil {49 log.Fatal(err)50 }51 containerLabels, err := mysqlContainer.Labels(ctx)52 if err != nil {

Full Screen

Full Screen

Source

Using AI Code Generation

copy

Full Screen

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

Full Screen

Full Screen

Source

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 _, b, _, _ := runtime.Caller(0)4 basepath := filepath.Dir(b)5 ctx := context.Background()6 req := testcontainers.ContainerRequest{7 ExposedPorts: []string{"8080/tcp"},8 WaitingFor: wait.ForHTTP("/").WithStartupTimeout(1 * time.Second),9 Cmd: []string{"--port",

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