How to use Ports method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.Ports

container.go

Source:container.go Github

copy

Full Screen

...18type Container struct {19 ctx context.Context20 container testcontainers.Container21 WaitingFor wait.Strategy22 Ports map[string]string23 Env map[string]string24 BindMounts map[string]string25 Image string26 Name string27 Address string28 ExposedPorts []string29 Logs TestLogConsumer30 Networks []string31 Entrypoint []string32}33func (c *Container) Start() error {34 c.ctx = context.Background()35 containerMounts := make([]testcontainers.ContainerMount, 0, len(c.BindMounts))36 for k, v := range c.BindMounts {37 containerMounts = append(containerMounts, testcontainers.BindMount(v, testcontainers.ContainerMountTarget(k)))38 }39 req := testcontainers.GenericContainerRequest{40 ContainerRequest: testcontainers.ContainerRequest{41 Mounts: testcontainers.Mounts(containerMounts...),42 Entrypoint: c.Entrypoint,43 Env: c.Env,44 ExposedPorts: c.ExposedPorts,45 Image: c.Image,46 Name: c.Name,47 Networks: c.Networks,48 WaitingFor: c.WaitingFor,49 },50 Started: true,51 }52 container, err := testcontainers.GenericContainer(c.ctx, req)53 if err != nil {54 return fmt.Errorf("container failed to start: %w", err)55 }56 c.container = container57 c.Logs = TestLogConsumer{58 Msgs: []string{},59 }60 c.container.FollowOutput(&c.Logs)61 err = c.container.StartLogProducer(c.ctx)62 if err != nil {63 return fmt.Errorf("log producer failed: %w", err)64 }65 c.Address = "localhost"66 err = c.LookupMappedPorts()67 if err != nil {68 _ = c.Terminate()69 return fmt.Errorf("port lookup failed: %w", err)70 }71 return nil72}73// create a lookup table of exposed ports to mapped ports74func (c *Container) LookupMappedPorts() error {75 if len(c.ExposedPorts) == 0 {76 return nil77 }78 if len(c.Ports) == 0 {79 c.Ports = make(map[string]string)80 }81 for _, port := range c.ExposedPorts {82 // strip off leading host port: 80:8080 -> 808083 if strings.Contains(port, ":") {84 port = strings.Split(port, ":")[1]85 }86 // strip off the transport: 80/tcp -> 8087 if strings.Contains(port, "/") {88 port = strings.Split(port, "/")[0]89 }90 p, err := c.container.MappedPort(c.ctx, nat.Port(port))91 if err != nil {92 return fmt.Errorf("failed to find '%s' - %w", port, err)93 }94 fmt.Printf("mapped container port '%s' to host port '%s'\n", port, p.Port())95 c.Ports[port] = p.Port()96 }97 return nil98}99func (c *Container) Exec(cmds []string) (int, error) {100 return c.container.Exec(c.ctx, cmds)101}102func (c *Container) PrintLogs() {103 fmt.Println("--- Container Logs Start ---")104 for _, msg := range c.Logs.Msgs {105 fmt.Print(msg)106 }107 fmt.Println("--- Container Logs End ---")108}109func (c *Container) Terminate() error {...

Full Screen

Full Screen

testcontainers.go

Source:testcontainers.go Github

copy

Full Screen

...6 "github.com/testcontainers/testcontainers-go/wait"7)8type TestContainers struct {9 env map[string]string10 publishPorts []string11 waitStrategy wait.Strategy12 containerMounts []testcontainers.ContainerMount13 noStart bool14 startupTimeout int15}16func NewTestContainers() TestContainers {17 return TestContainers{startupTimeout: 20}18}19func (r TestContainers) WithEnv(env map[string]string) TestContainers {20 r.env = env21 return r22}23func (r TestContainers) WithMounts(containerMounts ...testcontainers.ContainerMount) TestContainers {24 r.containerMounts = append(r.containerMounts, containerMounts...)25 return r26}27func (r TestContainers) WithExposedPorts(values ...string) TestContainers {28 r.publishPorts = append(r.publishPorts, values...)29 return r30}31func (r TestContainers) WithWaitingFor(waitStrategy wait.Strategy) TestContainers {32 r.waitStrategy = waitStrategy33 return r34}35func (r TestContainers) WithNoStart() TestContainers {36 r.noStart = true37 return r38}39func (r TestContainers) WithTimeout(t int) TestContainers {40 r.startupTimeout = t41 return r42}43func (r TestContainers) Execute(imageID string) (testcontainers.Container, error) {44 req := testcontainers.ContainerRequest{45 Image: imageID,46 ExposedPorts: r.publishPorts,47 WaitingFor: r.waitStrategy,48 Env: r.env,49 Mounts: r.containerMounts,50 SkipReaper: true,51 }52 c, cancel := context.WithTimeout(context.Background(), time.Second*time.Duration(r.startupTimeout))53 defer cancel()54 return testcontainers.GenericContainer(c, testcontainers.GenericContainerRequest{55 ContainerRequest: req,56 Started: !r.noStart,57 })58}...

Full Screen

Full Screen

testcontainer.go

Source:testcontainer.go Github

copy

Full Screen

...6 "strings"7 "github.com/testcontainers/testcontainers-go"8 "github.com/testcontainers/testcontainers-go/wait"9)10func SetupINetMockContainer(ctx context.Context, exposedPorts ...string) (testcontainers.Container, error) {11 //nolint:dogsled12 _, fileName, _, _ := runtime.Caller(0)13 var err error14 var repoRoot string15 if repoRoot, err = filepath.Abs(filepath.Join(filepath.Dir(fileName), "..", "..", "..")); err != nil {16 return nil, err17 }18 tcpPortPresent := false19 for _, port := range exposedPorts {20 if strings.Contains(port, "tcp") {21 tcpPortPresent = true22 }23 }24 if !tcpPortPresent {25 exposedPorts = append(exposedPorts, "80/tcp")26 }27 req := testcontainers.ContainerRequest{28 FromDockerfile: testcontainers.FromDockerfile{29 Context: repoRoot,30 Dockerfile: filepath.Join(".", "testdata", "integration.dockerfile"),31 PrintBuildLog: true,32 },33 ExposedPorts: exposedPorts,34 SkipReaper: true,35 WaitingFor: wait.ForLog("Startup of all endpoints completed"),36 }37 var imContainer testcontainers.Container38 imContainer, err = testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{39 ContainerRequest: req,40 Started: true,41 })42 if err != nil {43 return nil, err44 }45 return imContainer, nil46}...

Full Screen

Full Screen

Ports

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 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 port, err := redis.MappedPort(ctx, "6379/tcp")14 if err != nil {15 log.Fatal(err)16 }17 fmt.Println(port.Int())18}

Full Screen

Full Screen

Ports

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 mappedPort, _ := redisContainer.MappedPort(ctx, "6379")11 fmt.Println(mappedPort.Int())12 host, _ := redisContainer.Host(ctx)13 fmt.Println(host)14 id, _ := redisContainer.ContainerID(ctx)15 fmt.Println(id)16 info, _ := redisContainer.Inspect(ctx)17 fmt.Println(info.Name)18 logs, _ := redisContainer.Logs(ctx)19 fmt.Println(logs)20 redisContainer.Terminate(ctx)21}

Full Screen

Full Screen

Ports

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.Fatal(err)12 }13 defer redisContainer.Terminate(ctx)14 mappedPort, err := redisContainer.MappedPort(ctx, "6379/tcp")15 if err != nil {16 log.Fatal(err)17 }18 fmt.Printf("Redis port is %s", mappedPort.Port())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.Fatal(err)31 }32 defer redisContainer.Terminate(ctx)33 host, err := redisContainer.Host(ctx)34 if err != nil {35 log.Fatal(err)36 }37 fmt.Printf("Redis host is %s", host)38}39import (40func main() {41 ctx := context.Background()42 req := testcontainers.ContainerRequest{43 ExposedPorts: []string{"6379/tcp"},44 WaitingFor: wait.ForListeningPort("6379/tcp"),45 }46 redisContainer, err := testcontainers.GenericContainer(ctx

Full Screen

Full Screen

Ports

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 panic(err)12 }13 defer redisContainer.Terminate(ctx)14 redisPort, err := redisContainer.MappedPort(ctx, "6379/tcp")15 if err != nil {16 panic(err)17 }18 fmt.Println(redisPort.Int())19 time.Sleep(60 * time.Second)20}21import (22func main() {23 ctx := context.Background()24 req := testcontainers.ContainerRequest{25 ExposedPorts: []string{"6379/tcp"},26 WaitingFor: wait.ForListeningPort("6379/tcp"),27 }28 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{29 })30 if err != nil {31 panic(err)32 }33 defer redisContainer.Terminate(ctx)34 redisHost, err := redisContainer.Host(ctx)35 if err != nil {36 panic(err)37 }38 fmt.Println(redisHost)39 time.Sleep(60 * time.Second)40}

Full Screen

Full Screen

Ports

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

Full Screen

Full Screen

Ports

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, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatalf("Could not start container: %v", err)12 }13 defer postgres.Terminate(ctx)14 ip, err := postgres.Host(ctx)15 if err != nil {16 log.Fatalf("Could not get container IP: %v", err)17 }18 mappedPort, err := postgres.MappedPort(ctx, "5432/tcp")19 if err != nil {20 log.Fatalf("Could not get mapped port: %v", err)21 }22 fmt.Printf("Host: %s, Port: %s", ip, mappedPort.Port())

Full Screen

Full Screen

Ports

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("Hello from Docker!"),7 }8 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer container.Terminate(ctx)14 host, port, err := container.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 fmt.Println(host, port)19}

Full Screen

Full Screen

Ports

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, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer redisContainer.Terminate(ctx)14 redisPort, err := redisContainer.MappedPort(ctx, "6379")15 if err != nil {16 panic(err)17 }18 fmt.Println(redisPort.Int())19}

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