How to use MappedPort method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.MappedPort

psql_testcontainer.go

Source: psql_testcontainer.go Github

copy

Full Screen

...19 PostgreSQLContainerConfig struct {20 ImageTag string21 User string22 Password string23 MappedPort string24 Database string25 }26)27/​/​ GetDSN returns DB connection URL.28func (c PostgreSQLContainer) GetDSN() string {29 return fmt.Sprintf("postgres:/​/​%s:%s@localhost:%s/​%s?sslmode=disable", c.Config.User, c.Config.Password, c.Config.MappedPort, c.Config.Database)30}31func WithPostgreSQLTag(tag string) PostgreSQLContainerOption {32 return func(c *PostgreSQLContainerConfig) {33 c.ImageTag = tag34 }35}36func WithPostgreSQLDatabaseName(dbName string) PostgreSQLContainerOption {37 return func(c *PostgreSQLContainerConfig) {38 c.Database = dbName39 }40}41/​/​ NewPostgreSQLContainer creates and starts a PostgreSQL container.42func NewPostgreSQLContainer(ctx context.Context, opts ...PostgreSQLContainerOption) (*PostgreSQLContainer, error) {43 const (44 psqlImage = "postgres"45 psqlPort = "5432"46 )47 /​/​ Define container ENVs48 config := PostgreSQLContainerConfig{49 ImageTag: "11.5",50 User: "user",51 Password: "password",52 Database: "mockdb",53 }54 for _, opt := range opts {55 opt(&config)56 }57 containerPort := psqlPort + "/​tcp"58 /​/​ Build testcontainer request59 req := testcontainers.GenericContainerRequest{60 ContainerRequest: testcontainers.ContainerRequest{61 Env: map[string]string{62 "POSTGRES_USER": config.User,63 "POSTGRES_PASSWORD": config.Password,64 "POSTGRES_DB": config.Database,65 },66 ExposedPorts: []string{67 containerPort,68 },69 Image: fmt.Sprintf("%s:%s", psqlImage, config.ImageTag),70 SkipReaper: true,71 WaitingFor: wait.ForSQL(72 nat.Port(containerPort),73 "postgres",74 func(port nat.Port) string {75 return fmt.Sprintf("postgres:/​/​%s:%s@localhost:%s/​%s?sslmode=disable", config.User, config.Password, port.Port(), config.Database)76 }).77 Timeout(5 * time.Second),78 },79 Started: true,80 ProviderType: testcontainers.ProviderDocker,81 }82 /​/​ Create and run testcontainer83 provider, err := req.ProviderType.GetProvider()84 if err != nil {85 return nil, fmt.Errorf("getting request provider: %w", err)86 }87 container, err := provider.CreateContainer(ctx, req.ContainerRequest)88 if err != nil {89 return nil, fmt.Errorf("creating container: %w", err)90 }91 if err := container.Start(ctx); err != nil {92 return nil, fmt.Errorf("starting container: %w", err)93 }94 /​/​ Get mapped port for 5432/​tcp95 mappedPort, err := container.MappedPort(ctx, nat.Port(containerPort))96 if err != nil {97 return nil, fmt.Errorf("getting mapped port for (%s): %w", containerPort, err)98 }99 config.MappedPort = mappedPort.Port()100 return &PostgreSQLContainer{101 Container: container,102 Config: config,103 }, nil104}...

Full Screen

Full Screen

base_test.go

Source: base_test.go Github

copy

Full Screen

...48 ip, err := dbContainer.Host(ctx)49 if err != nil {50 log.Fatal(err)51 }52 mappedPort, err := dbContainer.MappedPort(ctx, "5432")53 if err != nil {54 log.Fatal(err)55 }56 i.cfg.Db.Host = ip57 i.cfg.Db.Port = mappedPort.Port()58 i.dbContainer = dbContainer59 if err := dbContainer.Start(ctx); err != nil {60 log.Fatal(err)61 }62 /​/​ auth63 req = testcontainers.ContainerRequest{64 Image: "auth-service:latest",65 ExposedPorts: []string{"3000/​tcp", "9000/​tcp"},66 WaitingFor: wait.ForLog("Grpc server started on port 3000"),67 }68 authContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{69 ContainerRequest: req,70 Started: true,71 })72 if err != nil {73 log.Fatal(err)74 }75 ip, err = authContainer.Host(ctx)76 if err != nil {77 log.Fatal(err)78 }79 mappedPort, err = authContainer.MappedPort(ctx, "3000")80 if err != nil {81 log.Fatal(err)82 }83 i.cfg.Auth.Host = ip84 i.cfg.Auth.Port = mappedPort.Port()85 i.authContainer = authContainer86 if err := authContainer.Start(ctx); err != nil {87 log.Fatal(err)88 }89 /​/​ Analytics service90 go application.Run(cfg)91 delayForRunningService := time.Second * 292 time.Sleep(delayForRunningService)93}...

Full Screen

Full Screen

redis_test_container.go

Source: redis_test_container.go Github

copy

Full Screen

...21 })22 if err != nil {23 return nil, err24 }25 mappedPort, err := container.MappedPort(ctx, "6379")26 if err != nil {27 return nil, err28 }29 hostIP, err := container.Host(ctx)30 if err != nil {31 return nil, err32 }33 addr := fmt.Sprintf("%s:%s", hostIP, mappedPort.Port())34 return &RedisTestContainer{Container: container, Addr: addr}, nil35}...

Full Screen

Full Screen

MappedPort

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"5432/​tcp"},6 WaitingFor: wait.ForListeningPort("5432/​tcp"),7 }8 postgres, _ := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 defer postgres.Terminate(ctx)11 port, _ := postgres.MappedPort(ctx, "5432/​tcp")12 fmt.Println(port.Int())13}

Full Screen

Full Screen

MappedPort

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.ForLog("Ready to accept connections"),7 }8 redisContainer, _ := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 defer redisContainer.Terminate(ctx)11 mappedPort, _ := redisContainer.MappedPort(ctx, "6379/​tcp")12 fmt.Println(mappedPort.Int())13}

Full Screen

Full Screen

MappedPort

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"6379/​tcp"},5 WaitingFor: wait.ForLog("Ready to accept connections"),6 }7 redisContainer, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{8 })9 if err != nil {10 log.Fatal(err)11 }12 defer redisContainer.Terminate(context.Background())13 redisHost, err := redisContainer.Host(context.Background())14 if err != nil {15 log.Fatal(err)16 }17 redisPort, err := redisContainer.MappedPort(context.Background(), "6379")18 if err != nil {19 log.Fatal(err)20 }21 fmt.Println(redisHost, redisPort.Int())22}

Full Screen

Full Screen

MappedPort

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 redisContainer, _ := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 redisHost, _ := redisContainer.Host(ctx)11 redisPort, _ := redisContainer.MappedPort(ctx, "6379/​tcp")12 fmt.Println("Redis Host: " + redisHost)13 fmt.Println("Redis Port: " + redisPort.Port())14 time.Sleep(5 * time.Second)15 redisContainer.Terminate(ctx)16}

Full Screen

Full Screen

MappedPort

Using AI Code Generation

copy

Full Screen

1func TestMappedPort(t *testing.T) {2 ctx := context.Background()3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"6379/​tcp"},5 WaitingFor: wait.ForListeningPort("6379/​tcp"),6 }7 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{8 })9 if err != nil {10 panic(err)11 }12 defer redis.Terminate(ctx)13 mappedPort, err := redis.MappedPort(ctx, "6379/​tcp")14 if err != nil {15 panic(err)16 }17 fmt.Printf("Mapped port: %s", mappedPort.Port())18}19func TestHost(t *testing.T) {20 ctx := context.Background()21 req := testcontainers.ContainerRequest{22 ExposedPorts: []string{"6379/​tcp"},23 WaitingFor: wait.ForListeningPort("6379/​tcp"),24 }25 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{26 })27 if err != nil {28 panic(err)29 }30 defer redis.Terminate(ctx)31 host, err := redis.Host(ctx)32 if err != nil {33 panic(err)34 }35 fmt.Printf("Host: %s", host)36}37func TestPort(t *testing.T) {38 ctx := context.Background()39 req := testcontainers.ContainerRequest{40 ExposedPorts: []string{"6379/​tcp"},41 WaitingFor: wait.ForListeningPort("6379/​tcp"),42 }43 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{44 })45 if err != nil {46 panic(err)47 }48 defer redis.Terminate(ctx)49 port, err := redis.Port(ctx, "6379/​tcp")50 if err != nil {51 panic(err)52 }53 fmt.Printf("Port: %s", port)54}55func TestStart(t *testing.T) {

Full Screen

Full Screen

MappedPort

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 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatalf("Could not start container: %v", err)12 }13 defer redisContainer.Terminate(ctx)14 port, err := redisContainer.MappedPort(ctx, "6379/​tcp")15 if err != nil {16 log.Fatalf("Could not get the mapped port: %v", err)17 }18 host, err := redisContainer.Host(ctx)19 if err != nil {20 log.Fatalf("Could not get the container host: %v", err)21 }22 conn, err := net.Dial("tcp", fmt.Sprintf("%s:%s", host, port.Port()))23 if err != nil {24 log.Fatalf("Could not connect to container: %v", err)25 }26 defer conn.Close()27 fmt.Println("Connected to Redis!")28}

Full Screen

Full Screen

MappedPort

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 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 port, err := container.MappedPort(ctx, "80")14 if err != nil {15 log.Fatal(err)16 }17 ip, err := container.Host(ctx)18 if err != nil {19 log.Fatal(err)20 }21 time.Sleep(5 * time.Second)22 resp, err := http.Get(url)23 if err != nil {24 log.Fatal(err)25 }26 fmt.Println(resp.Status)27 err = container.Terminate(ctx)28 if err != nil {29 log.Fatal(err)30 }31 os.Exit(0)32}33import (34func main() {35 ctx := context.Background()36 req := testcontainers.ContainerRequest{

Full Screen

Full Screen

MappedPort

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 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatalf("Could not start container: %v", err)12 }13 mappedPort, err := redisContainer.MappedPort(ctx, "6379")14 if err != nil {15 log.Fatalf("Could not get port: %v", err)16 }17 fmt.Println(mappedPort.Int())18 redisContainer.Terminate(ctx)19}20import (21func main() {22 ctx := context.Background()23 req := testcontainers.ContainerRequest{24 ExposedPorts: []string{"6379/​tcp"},25 WaitingFor: wait.ForListeningPort("6379/​tcp"),26 }27 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{28 })29 if err != nil {30 log.Fatalf("Could not start container: %v", err)31 }32 host, err := redisContainer.Host(ctx)33 if err != nil {34 log.Fatalf("Could not get host: %v", err)35 }36 mappedPort, err := redisContainer.MappedPort(ctx, "6379")37 if err != nil {38 log.Fatalf("Could not get port: %v", err

Full Screen

Full Screen

MappedPort

Using AI Code Generation

copy

Full Screen

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 defer postgresContainer.Terminate(ctx)14 port, err := postgresContainer.MappedPort(ctx, "5432/​tcp")15 if err != nil {16 log.Fatal(err)17 }18 fmt.Println(port.Int())19 time.Sleep(10 * time.Second)20}21import (22func main() {23 ctx := context.Background()24 req := testcontainers.ContainerRequest{25 ExposedPorts: []string{"5432/​tcp"},26 WaitingFor: wait.ForListeningPort("5432/​tcp"),27 }28 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{29 })30 if err != nil {31 log.Fatal(err)32 }33 defer postgresContainer.Terminate(ctx)34 ip, err := postgresContainer.ContainerIP(ctx)

Full Screen

Full Screen

Blogs

Check out the latest blogs from LambdaTest on this topic:

How To Get Started With Cypress Debugging

One of the most important tasks of a software developer is not just writing code fast; it is the ability to find what causes errors and bugs whenever you encounter one and the ability to solve them quickly.

A Reconsideration of Software Testing Metrics

There is just one area where each member of the software testing community has a distinct point of view! Metrics! This contentious issue sparks intense disputes, and most conversations finish with no definitive conclusion. It covers a wide range of topics: How can testing efforts be measured? What is the most effective technique to assess effectiveness? Which of the many components should be quantified? How can we measure the quality of our testing performance, among other things?

Your Favorite Dev Browser Has Evolved! The All New LT Browser 2.0

We launched LT Browser in 2020, and we were overwhelmed by the response as it was awarded as the #5 product of the day on the ProductHunt platform. Today, after 74,585 downloads and 7,000 total test runs with an average of 100 test runs each day, the LT Browser has continued to help developers build responsive web designs in a jiffy.

Getting Started with SpecFlow Actions [SpecFlow Automation Tutorial]

With the rise of Agile, teams have been trying to minimize the gap between the stakeholders and the development team.

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