Best Testcontainers-go code snippet using testcontainers.Connect
database.go
Source:database.go
...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 = database...
manager_test.go
Source:manager_test.go
...43 os.Setenv("CLICKHOUSE_DB_PORT", p.Port())44 defer clickhouseContainer.Terminate(ctx) //nolint45 os.Exit(m.Run())46}47func TestConnect(t *testing.T) {48 mappedPort, err := strconv.Atoi(os.Getenv("CLICKHOUSE_DB_PORT"))49 if err != nil {50 t.Fatal("Unable to read port value from environment")51 }52 t.Run("can only connect once", func(t *testing.T) {53 // get before connection54 manager := platform.GetResourceManager()55 require.Nil(t, manager.DbClient)56 // init connection57 err = manager.Connect("localhost", uint16(mappedPort), "", "")58 require.Nil(t, err)59 require.NotNil(t, manager.DbClient)60 // try and re-fetch connection61 err = manager.Connect("localhost", uint16(mappedPort), "", "")62 require.NotNil(t, err)63 require.Equal(t, "connect can only be called once", err.Error())64 })65}66func TestGetResourceManager(t *testing.T) {67 t.Run("get resource manager", func(t *testing.T) {68 manager := platform.GetResourceManager()69 require.NotNil(t, manager)70 manager2 := platform.GetResourceManager()71 require.NotNil(t, manager2)72 require.Equal(t, &manager, &manager2)73 })74}...
mqttdevice_test.go
Source:mqttdevice_test.go
...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}...
Connect
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"5432/tcp"},6 WaitingFor: wait.ForListeningPort("5432/tcp"),7 }8 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 ip, err := postgresContainer.Host(ctx)14 if err != nil {15 panic(err)16 }17 port, err := postgresContainer.MappedPort(ctx, "5432/tcp")18 if err != nil {19 panic(err)20 }21 connStr := fmt.Sprintf("host=%s port=%s user=postgres password=postgres dbname=postgres sslmode=disable", ip, port.Port())22 db, err := sql.Open("postgres", connStr)23 if err != nil {24 panic(err)25 }26 defer db.Close()27 _, err = db.Exec("CREATE TABLE IF NOT EXISTS test (id int)")28 if err != nil {29 panic(err)30 }31 _, err = db.Exec("INSERT INTO test (id) VALUES (1)")32 if err != nil {33 panic(err)34 }35 _, err = db.Exec("INSERT INTO test (id) VALUES (2)")36 if err != nil {37 panic(err)38 }39 _, err = db.Exec("INSERT INTO test (id) VALUES (3)")40 if err != nil {41 panic(err)42 }43 rows, err := db.Query("SELECT * FROM test")44 if err != nil {45 panic(err)46 }47 for rows.Next() {48 err = rows.Scan(&id)49 if err != nil {50 panic(err)51 }
Connect
Using AI Code Generation
1import (2func main() {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 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.Println("host=", ip, "port=", port.Int())23}
Connect
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"5432/tcp"},6 WaitingFor: wait.ForListeningPort("5432/tcp"),7 }8 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 postgresContainer.Terminate(ctx)14}15import (16func main() {17 ctx := context.Background()18 req := testcontainers.ContainerRequest{19 ExposedPorts: []string{"5432/tcp"},20 WaitingFor: wait.ForListeningPort("5432/tcp"),21 }22 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{23 })24 if err != nil {25 log.Fatal(err)26 }27 postgresContainer.Terminate(ctx)28}29import (30func main() {31 ctx := context.Background()32 req := testcontainers.ContainerRequest{33 ExposedPorts: []string{"5432/tcp"},34 WaitingFor: wait.ForListeningPort("5432/tcp"),35 }36 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{37 })38 if err != nil {39 log.Fatal(err)40 }
Connect
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"5432/tcp"},6 WaitingFor: testcontainers.WaitingForListeningPort("5432/tcp"),7 }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 log.Printf("postgres is available on %s:%s", ip, port.Port())23 time.Sleep(10 * time.Second)24}
Connect
Using AI Code Generation
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 mappedPort, err := nginxContainer.MappedPort(ctx, "80")19 if err != nil {20 log.Fatal(err)21 }22 resp, err := http.Get(url)23 if err != nil {24 log.Fatal(err)25 }26 fmt.Printf("Response: %s", resp.Status)27}
Connect
Using AI Code Generation
1import (2func main() {3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"5432/tcp"},5 WaitingFor: wait.ForListeningPort("5432/tcp"),6 Env: map[string]string{"POSTGRES_PASSWORD": "password"},7 }8 ctx := context.Background()9 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 log.Fatal(err)13 }14 defer postgresContainer.Terminate(ctx)15 ip, err := postgresContainer.Host(ctx)16 if err != nil {17 log.Fatal(err)18 }19 port, err := postgresContainer.MappedPort(ctx, "5432/tcp")20 if err != nil {21 log.Fatal(err)22 }23 fmt.Println(ip, port.Int())24 time.Sleep(5 * time.Second)25}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!