Best Testcontainers-go code snippet using testcontainers.createTestContainer
db.go
Source:db.go
1package testutil2import (3 "context"4 "database/sql"5 "fmt"6 "log"7 "path/filepath"8 "runtime"9 "time"10 "github.com/docker/go-connections/nat"11 "github.com/golang-migrate/migrate/v4"12 "github.com/golang-migrate/migrate/v4/database/postgres"13 testcontainers "github.com/testcontainers/testcontainers-go"14 "github.com/testcontainers/testcontainers-go/wait"15)16const (17 dbName = "jenkins_usage_stats_test"18)19// Fataler interface has a single method Fatal, which takes20// a slice of arguments and is expected to panic.21type Fataler interface {22 Fatal(args ...interface{})23}24// DBForTest spins up a postgres container, creates the test database on it, migrates it, and returns the db and a close function25func DBForTest(f Fataler) (*sql.DB, func()) {26 ctx := context.Background()27 // container and database28 container, db, err := CreateTestContainer(ctx)29 if err != nil {30 f.Fatal(err)31 }32 closeFunc := func() {33 _ = db.Close()34 _ = container.Terminate(ctx)35 }36 // migration37 mig, err := NewPgMigrator(db)38 if err != nil {39 closeFunc()40 f.Fatal(err)41 }42 err = mig.Up()43 if err != nil {44 closeFunc()45 f.Fatal(err)46 }47 return db, closeFunc48}49// CreateTestContainer spins up a Postgres database container50func CreateTestContainer(ctx context.Context) (testcontainers.Container, *sql.DB, error) {51 env := map[string]string{52 "POSTGRES_PASSWORD": "password",53 "POSTGRES_USER": "postgres",54 "POSTGRES_DB": dbName,55 }56 dockerPort := "5432/tcp"57 dbURL := func(port nat.Port) string {58 return fmt.Sprintf("postgres://postgres:password@localhost:%s/%s?sslmode=disable", port.Port(), dbName)59 }60 req := testcontainers.GenericContainerRequest{61 ContainerRequest: testcontainers.ContainerRequest{62 Image: "postgres:12",63 ExposedPorts: []string{dockerPort},64 Cmd: []string{"postgres", "-c", "fsync=off"},65 Env: env,66 WaitingFor: wait.ForSQL(nat.Port(dockerPort), "postgres", dbURL).Timeout(time.Second * 30),67 },68 Started: true,69 }70 container, err := testcontainers.GenericContainer(ctx, req)71 if err != nil {72 return container, nil, fmt.Errorf("failed to start container: %s", err)73 }74 mappedPort, err := container.MappedPort(ctx, nat.Port(dockerPort))75 if err != nil {76 return container, nil, fmt.Errorf("failed to get container external port: %s", err)77 }78 log.Println("postgres container ready and running at dockerPort: ", mappedPort)79 url := fmt.Sprintf("postgres://postgres:password@localhost:%s/%s?sslmode=disable", mappedPort.Port(), dbName)80 db, err := sql.Open("postgres", url)81 if err != nil {82 return container, db, fmt.Errorf("failed to establish database connection: %s", err)83 }84 return container, db, nil85}86// NewPgMigrator creates a migrator instance87func NewPgMigrator(db *sql.DB) (*migrate.Migrate, error) {88 _, path, _, ok := runtime.Caller(0)89 if !ok {90 log.Fatalf("failed to get path")91 }92 sourceURL := "file://" + filepath.Dir(path) + "/../etc/migrations"93 driver, err := postgres.WithInstance(db, &postgres.Config{})94 if err != nil {95 log.Fatalf("failed to create migrator driver: %s", err)96 }97 m, err := migrate.NewWithDatabaseInstance(sourceURL, "postgres", driver)98 return m, err99}...
testcontainer.go
Source:testcontainer.go
1package data2import (3 "context"4 "database/sql"5 "fmt"6 "log"7 "time"8 "github.com/docker/go-connections/nat"9 _ "github.com/lib/pq"10 "github.com/testcontainers/testcontainers-go"11 "github.com/testcontainers/testcontainers-go/wait"12)13// CreateTestContainer initalizes the container that runs the test database14func CreateTestContainer(ctx context.Context, dbname string) (testcontainers.Container, *sql.DB, error) {15 var env = map[string]string{16 "POSTGRES_PASSWORD": "password",17 "POSTGRES_USER": "postgres",18 "POSTGRES_DB": dbname,19 }20 var port = "5432/tcp"21 dbURL := func(port nat.Port) string {22 return fmt.Sprintf("postgres://postgres:password@localhost:%s/%s?sslmode=disable", port.Port(), dbname)23 }24 req := testcontainers.GenericContainerRequest{25 ContainerRequest: testcontainers.ContainerRequest{26 Image: "postgres:latest",27 ExposedPorts: []string{port},28 Cmd: []string{"postgres", "-c", "fsync=off"},29 Env: env,30 WaitingFor: wait.ForSQL(nat.Port(port), "postgres", dbURL).Timeout(time.Second * 5),31 },32 Started: true,33 }34 container, err := testcontainers.GenericContainer(ctx, req)35 if err != nil {36 return container, nil, fmt.Errorf("failed to start container: %s", err)37 }38 mappedPort, err := container.MappedPort(ctx, nat.Port(port))39 if err != nil {40 return container, nil, fmt.Errorf("failed to get container external port: %s", err)41 }42 log.Println("postgres container ready and running at port: ", mappedPort)43 url := fmt.Sprintf("postgres://postgres:password@localhost:%s/%s?sslmode=disable", mappedPort.Port(), dbname)44 db, err := sql.Open("postgres", url)45 if err != nil {46 return container, db, fmt.Errorf("failed to establish database connection: %s", err)47 }48 return container, db, nil49}...
containers.go
Source:containers.go
1package helpertest2import (3 "context"4 "testing"5 "github.com/docker/go-connections/nat"6 "github.com/testcontainers/testcontainers-go"7)8// ContainerRequest simplifies the params given to CreateTestContainer, supplying its input requirement to generate9// the desired container and an easy way to request which port was effectively mapped.10type ContainerRequest struct {11 Request testcontainers.ContainerRequest12 PortToMap string13}14// TestContainer combines the requested container return and the effectively mapped port.15type TestContainer struct {16 Container testcontainers.Container17 MappedPort nat.Port18}19// CreateTestContainer is used to create docker containers that are to be used only for functional tests. Always remember to set its related Envs and terminate with a defer20func CreateTestContainer(ctx context.Context, t *testing.T, containerRequest ContainerRequest) (testContainer TestContainer) {21 container, err := startContainer(ctx, containerRequest.Request)22 if err != nil {23 t.Fatalf("[ helper ] failed to start container: %v\n", err)24 }25 port, err := container.MappedPort(ctx, nat.Port(containerRequest.PortToMap))26 if err != nil {27 t.Fatalf("[ helper ] failed to get mapped port: %v\n", err)28 }29 testContainer = TestContainer{30 Container: container,31 MappedPort: port,32 }33 return34}35func startContainer(ctx context.Context, request testcontainers.ContainerRequest) (testcontainers.Container, error) {36 return testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{37 ContainerRequest: request,38 Started: true,39 })40}...
createTestContainer
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"9200/tcp"},6 WaitingFor: wait.ForLog("started"),7 }8 elasticsearchContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatalf("Could not start container: %s", err)12 }13 defer elasticsearchContainer.Terminate(ctx)14 ip, err := elasticsearchContainer.Host(ctx)15 if err != nil {16 log.Fatalf("Could not get container IP: %s", err)17 }18 port, err := elasticsearchContainer.MappedPort(ctx, "9200")19 if err != nil {20 log.Fatalf("Could not get container port: %s", err)21 }22}23require (
createTestContainer
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"5432/tcp"},6 Env: map[string]string{"POSTGRES_PASSWORD": "password"},7 WaitingFor: wait.ForLog("database system is ready to accept connections"),8 }9 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 panic(err)13 }14 defer postgresContainer.Terminate(ctx)15 ip, err := postgresContainer.Host(ctx)16 if err != nil {17 panic(err)18 }19 port, err := postgresContainer.MappedPort(ctx, "5432")20 if err != nil {21 panic(err)22 }23 fmt.Println(ip, port.Int())24 time.Sleep(30 * time.Second)25}26import (27func main() {28 ctx := context.Background()29 req := testcontainers.ContainerRequest{30 ExposedPorts: []string{"5432/tcp"},31 Env: map[string]string{"POSTGRES_PASSWORD": "password"},32 WaitingFor: wait.ForLog("database system is ready to accept connections"),33 }34 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{35 })36 if err != nil {37 panic(err)38 }39 defer postgresContainer.Terminate(ctx)40 ip, err := postgresContainer.Host(ctx)41 if err != nil {42 panic(err)43 }44 port, err := postgresContainer.MappedPort(ctx, "5432")45 if err != nil {46 panic(err)47 }48 fmt.Println(ip, port.Int())49 time.Sleep(30 * time.Second)50}51import (
createTestContainer
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 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 port, err := container.MappedPort(ctx, "5432")14 if err != nil {15 log.Fatal(err)16 }17 fmt.Println(port.Int())18}19require (
createTestContainer
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 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatalf("Could not start container: %v", err)12 }13 ip, err := c.Host(ctx)14 if err != nil {15 log.Fatalf("Could not get host: %v", err)16 }17 port, err := c.MappedPort(ctx, "80")18 if err != nil {19 log.Fatalf("Could not get port: %v", err)20 }21 id, err := c.ContainerID(ctx)22 if err != nil {23 log.Fatalf("Could not get container id: %v", err)24 }25 name, err := c.ContainerName(ctx)26 if err != nil {27 log.Fatalf("Could not get container name: %v", err)28 }29 state, err := c.ContainerState(ctx)30 if err != nil {31 log.Fatalf("Could not get container state: %v", err)32 }33 logs, err := c.Logs(ctx)34 if err != nil {35 log.Fatalf("Could not get container logs: %v", err)36 }37 image, err := c.Image(ctx)38 if err != nil {39 log.Fatalf("Could not get container image: %v", err)40 }41 platform, err := c.Platform(ctx)42 if err != nil {43 log.Fatalf("Could not get container platform: %v", err)44 }45 labels, err := c.Labels(ctx)46 if err != nil {47 log.Fatalf("Could not get container labels: %v", err)48 }
createTestContainer
Using AI Code Generation
1import (2func main() {3 containerId := createTestContainer()4 runTestCases(containerId)5}6func runTestCases(containerId string) {7 cmd := exec.Command("docker", "exec", containerId, "go", "test", "-v")8 output, err := cmd.Output()9 if err != nil {10 fmt.Println(err)11 }12 fmt.Println(string(output))13}14func createTestContainer() string {15 cmd := exec.Command("docker", "create", "golang:latest")16 output, err := cmd.Output()17 if err != nil {18 fmt.Println(err)19 }
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!!