Best Testcontainers-go code snippet using testcontainers.Start
testing_kafka_cluster.go
Source:testing_kafka_cluster.go
...18type TestingKafkaCluster struct {19 kafkaContainer testcontainers.Container20 zookeeperContainer testcontainers.Container21}22func (kc *TestingKafkaCluster) StartCluster() error {23 ctx := context.Background()24 if err := kc.zookeeperContainer.Start(ctx); err != nil {25 return err26 }27 if err := kc.kafkaContainer.Start(ctx); err != nil {28 return err29 }30 if err := kc.createProbe(); err != nil {31 return err32 }33 return kc.startKafka()34}35func (kc *TestingKafkaCluster) StopCluster() error {36 ctx := context.Background()37 if err := kc.kafkaContainer.Terminate(ctx); err != nil {38 return err39 }40 if err := kc.zookeeperContainer.Terminate(ctx); err != nil {41 return err42 }43 return nil44}45func (kc *TestingKafkaCluster) GetKafkaHost() (string, error) {46 ctx := context.Background()47 host, err := kc.kafkaContainer.Host(ctx)48 if err != nil {49 return "", err50 }51 port, err := kc.kafkaContainer.MappedPort(ctx, KAFKA_CLIENT_PORT)52 if err != nil {53 return "", err54 }55 return host + ":" + port.Port(), nil56}57func (kc *TestingKafkaCluster) createProbe() error {58 probeScript, err := ioutil.TempFile("", "probe.sh")59 if err != nil {60 return err61 }62 defer os.Remove(probeScript.Name())63 probeScript.WriteString("#!/bin/bash \n")64 probeScript.WriteString(fmt.Sprintf("id=$(zookeeper-shell localhost:%s ls /brokers/ids | grep \"\\[%s\") \n", ZOOKEEPER_PORT, KAFKA_BROKER_ID))65 probeScript.WriteString(fmt.Sprintf("if [ $id = \"[%s]\" ]; then exit 0; else exit 1; fi", KAFKA_BROKER_ID))66 return kc.zookeeperContainer.CopyFileToContainer(context.Background(), probeScript.Name(), "probe.sh", 0700)67}68func (kc *TestingKafkaCluster) startKafka() error {69 ctx := context.Background()70 kafkaStartFile, err := ioutil.TempFile("", "testcontainers_start.sh")71 if err != nil {72 return err73 }74 defer os.Remove(kafkaStartFile.Name())75 exposedHost, err := kc.GetKafkaHost()76 if err != nil {77 return err78 }79 kafkaStartFile.WriteString("#!/bin/bash \n")80 kafkaStartFile.WriteString(fmt.Sprintf("export KAFKA_ADVERTISED_LISTENERS='PLAINTEXT://%s,BROKER://kafka:%s'\n", exposedHost, KAFKA_BROKER_PORT))81 kafkaStartFile.WriteString(". /etc/confluent/docker/bash-config \n")82 kafkaStartFile.WriteString("/etc/confluent/docker/configure \n")83 kafkaStartFile.WriteString("/etc/confluent/docker/launch \n")84 return kc.kafkaContainer.CopyFileToContainer(ctx, kafkaStartFile.Name(), "testcontainers_start.sh", 0700)85}86func NewTestingKafkaCluster() (*TestingKafkaCluster, error) {87 ctx := context.Background()88 network, err := testcontainers.GenericNetwork(ctx, testcontainers.GenericNetworkRequest{89 NetworkRequest: testcontainers.NetworkRequest{Name: CLUSTER_NETWORK_NAME},90 })91 if err != nil {92 return nil, err93 }94 dockerNetwork := network.(*testcontainers.DockerNetwork)95 zookeeperContainer, err := createZookeeperContainer(dockerNetwork)96 if err != nil {97 return nil, err98 }...
kafkacluster.go
Source:kafkacluster.go
...16type KafkaCluster struct {17 kafkaContainer testcontainers.Container18 zookeeperContainer testcontainers.Container19}20func (kc *KafkaCluster) StartCluster() {21 ctx := context.Background()22 kc.zookeeperContainer.Start(ctx)23 kc.kafkaContainer.Start(ctx)24 kc.startKafka()25}26func (kc *KafkaCluster) GetKafkaHost() string {27 ctx := context.Background()28 host, err := kc.kafkaContainer.Host(ctx)29 if err != nil {30 panic(err)31 }32 port, err := kc.kafkaContainer.MappedPort(ctx, KAFKA_CLIENT_PORT)33 if err != nil {34 panic(err)35 }36 // returns the exposed kafka host:port37 return host + ":" + port.Port()38}39func (kc *KafkaCluster) startKafka() {40 ctx := context.Background()41 kafkaStartFile, err := ioutil.TempFile("", "testcontainers_start.sh")42 if err != nil {43 panic(err)44 }45 defer os.Remove(kafkaStartFile.Name())46 // needs to set KAFKA_ADVERTISED_LISTENERS with the exposed kafka port47 exposedHost := kc.GetKafkaHost()48 kafkaStartFile.WriteString("#!/bin/bash \n")49 kafkaStartFile.WriteString("export KAFKA_ADVERTISED_LISTENERS='PLAINTEXT://" + exposedHost + ",BROKER://kafka:" + KAFKA_BROKER_PORT + "'\n")50 kafkaStartFile.WriteString(". /etc/confluent/docker/bash-config \n")51 kafkaStartFile.WriteString("/etc/confluent/docker/configure \n")52 kafkaStartFile.WriteString("/etc/confluent/docker/launch \n")53 err = kc.kafkaContainer.CopyFileToContainer(ctx, kafkaStartFile.Name(), "testcontainers_start.sh", 0700)54 if err != nil {55 panic(err)56 }57}58func NewKafkaCluster() *KafkaCluster {59 ctx := context.Background()60 // creates a network, so kafka and zookeeper can communicate directly61 network, err := testcontainers.GenericNetwork(ctx, testcontainers.GenericNetworkRequest{62 NetworkRequest: testcontainers.NetworkRequest{Name: CLUSTER_NETWORK_NAME},63 })64 if err != nil {65 panic(err)66 }67 dockerNetwork := network.(*testcontainers.DockerNetwork)...
testcontainers.go
Source:testcontainers.go
...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}...
Start
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"27017/tcp"},6 WaitingFor: wait.ForListeningPort("27017/tcp"),7 }8 mongo, _ := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 defer mongo.Terminate(ctx)11 ip, _ := mongo.Host(ctx)12 port, _ := mongo.MappedPort(ctx, "27017")13}14import (15func main() {16 ctx := context.Background()17 req := testcontainers.ContainerRequest{18 ExposedPorts: []string{"27017/tcp"},19 WaitingFor: wait.ForListeningPort("27017/tcp"),20 }21 mongo, _ := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{22 })23 defer mongo.Terminate(ctx)24 ip, _ := mongo.Host(ctx)25 port, _ := mongo.MappedPort(ctx, "27017")26}27import (28func main() {29 ctx := context.Background()30 req := testcontainers.ContainerRequest{31 ExposedPorts: []string{"27017/tcp"},32 WaitingFor: wait.ForListeningPort("27017/tcp"),33 }34 mongo, _ := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{35 })36 defer mongo.Terminate(ctx)37 ip, _ := mongo.Host(ctx)
Start
Using AI Code Generation
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 panic(err)12 }13 defer redis.Terminate(ctx)14 ip, err := redis.Host(ctx)15 if err != nil {16 panic(err)17 }18 mappedPort, err := redis.MappedPort(ctx, "6379")19 if err != nil {20 panic(err)21 }22 fmt.Printf("Redis is available at %s:%s", ip, mappedPort.Port())23}
Start
Using AI Code Generation
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 log.Fatal(err)12 }13 defer redisContainer.Terminate(ctx)14 redisPort, err := redisContainer.MappedPort(ctx, "6379/tcp")15 if err != nil {16 log.Fatal(err)17 }18 fmt.Println(redisPort.Int())19 time.Sleep(10 * time.Minute)20}21import (22func main() {23 ctx := context.Background()24 req := testcontainers.ContainerRequest{25 ExposedPorts: []string{"6379/tcp"},26 WaitingFor: wait.ForLog("Ready to accept connections"),27 }28 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{29 })30 if err != nil {31 log.Fatal(err)32 }33 defer redisContainer.Terminate(ctx)34 redisPort, err := redisContainer.MappedPort(ctx, "6379/tcp")35 if err != nil {36 log.Fatal(err)37 }38 fmt.Println(redisPort.Int())39 time.Sleep(10 * time.Minute)40}41import (
Start
Using AI Code Generation
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 log.Fatal(err)12 }13 defer redisContainer.Terminate(ctx)14 ip, err := redisContainer.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := redisContainer.MappedPort(ctx, "6379")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println(ip, port.Int())23 time.Sleep(10 * time.Minute)24}
Start
Using AI Code Generation
1import (2func TestStart(t *testing.T) {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 WaitingFor: wait.ForLog("Ready to accept connections"),6 }7 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{8 })9 if err != nil {10 log.Fatalf("Could not start container: %v", err)11 }12 defer redisContainer.Terminate(ctx)13 ip, err := redisContainer.Host(ctx)14 if err != nil {15 log.Fatalf("Could not get container IP: %v", err)16 }17 port, err := redisContainer.MappedPort(ctx, "6379/tcp")18 if err != nil {19 log.Fatalf("Could not get container port: %v", err)20 }21 fmt.Printf("Container port is %d, IP is %s\n", port.Int(), ip)22}
Start
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 WaitingFor: wait.ForHTTP("/").WithStartupTimeout(1 * time.Minute),7 }8 nginxContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 ip, err := nginxContainer.Host(ctx)14 if err != nil {15 log.Fatal(err)16 }17 port, err := nginxContainer.MappedPort(ctx, "80")18 if err != nil {19 log.Fatal(err)20 }21 if err != nil {22 log.Fatal(err)23 }24 fmt.Println(resp.Status)25 err = nginxContainer.Terminate(ctx)26 if err != nil {27 log.Fatal(err)28 }29 err = nginxContainer.Remove(ctx)30 if err != nil {31 log.Fatal(err)32 }33}
Start
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 port, err := postgresContainer.MappedPort(ctx, "5432")14 if err != nil {15 panic(err)16 }17 fmt.Println("Postgres port is: ", port.Int())18 os.Exit(0)19}20import (21func main() {22 ctx := context.Background()23 req := testcontainers.ContainerRequest{24 ExposedPorts: []string{"5432/tcp"},25 WaitingFor: wait.ForListeningPort("5432/tcp"),26 }27 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{28 })29 if err != nil {30 panic(err)31 }32 port, err := postgresContainer.MappedPort(ctx, "5432")33 if err != nil {34 panic(err)35 }36 fmt.Println("Postgres port is: ", port.Int())37 postgresContainer.Terminate(ctx)38 os.Exit(0)39}40import (41func main() {42 ctx := context.Background()43 req := testcontainers.ContainerRequest{44 ExposedPorts: []string{"5432/tcp"},45 WaitingFor: wait.ForListeningPort("5432/tcp"),46 }47 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
Start
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"3306/tcp"},6 WaitingFor: wait.ForListeningPort("3306/tcp"),7 }8 mysqlContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer mysqlContainer.Terminate(ctx)14 port, err := mysqlContainer.MappedPort(ctx, "3306")15 if err != nil {16 log.Fatal(err)17 }18 ip, err := mysqlContainer.Host(ctx)19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println(port.Int())23 fmt.Println(ip)24}
Start
Using AI Code Generation
1import (2func main() {3 fmt.Println("Welcome to Testcontainers")4 ctx := context.Background()5 req := testcontainers.ContainerRequest{6 ExposedPorts: []string{"6379/tcp"},7 WaitingFor: wait.ForLog("Ready to accept connections"),8 }9 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{10 })11 if err != nil {12 log.Fatal(err)13 }14 defer redisContainer.Terminate(ctx)15 ip, err := redisContainer.Host(ctx)16 if err != nil {17 log.Fatal(err)18 }19 port, err := redisContainer.MappedPort(ctx, "6379/tcp")20 if err != nil {21 log.Fatal(err)22 }23 fmt.Printf("Container IP: %s, Port: %s", ip, port.Port())24 time.Sleep(5 * time.Minute)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!!