How to use Type method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.Type

e2e_test.go

Source:e2e_test.go Github

copy

Full Screen

1package e2etests2import (3 "context"4 "encoding/json"5 "fmt"6 "io/ioutil"7 "net/http"8 "os"9 "testing"10 "time"11 clickhouse "github.com/ClickHouse/clickhouse-go/v2"12 "github.com/ecodia/golang-awaitility/awaitility"13 "github.com/stretchr/testify/assert"14 "github.com/stretchr/testify/require"15 testcontainers "github.com/testcontainers/testcontainers-go"16 "github.com/testcontainers/testcontainers-go/wait"17)18const (19 clickHouseImage = "clickhouse/clickhouse-server:22"20 jaegerImage = "jaegertracing/all-in-one:1.32.0"21 networkName = "chi-jaeger-test"22 clickhousePort = "9000/tcp"23 jaegerQueryPort = "16686/tcp"24 jaegerAdminPort = "14269/tcp"25)26type testCase struct {27 configs []string28 chiconf *string29}30func TestE2E(t *testing.T) {31 if os.Getenv("E2E_TEST") == "" {32 t.Skip("Set E2E_TEST=true to run the test")33 }34 // Minimal additional configuration (config.d) to enable cluster mode35 chireplconf := "clickhouse-replicated.xml"36 tests := map[string]testCase{37 "local-single": {38 configs: []string{"config-local-single.yaml"},39 chiconf: nil,40 },41 "local-multi": {42 configs: []string{"config-local-multi1.yaml", "config-local-multi2.yaml"},43 chiconf: nil,44 },45 "replication-single": {46 configs: []string{"config-replication-single.yaml"},47 chiconf: &chireplconf,48 },49 "replication-multi": {50 configs: []string{"config-replication-multi1.yaml", "config-replication-multi2.yaml"},51 chiconf: &chireplconf,52 },53 }54 for name, test := range tests {55 t.Run(name, func(t *testing.T) {56 testE2E(t, test)57 })58 }59}60func testE2E(t *testing.T, test testCase) {61 ctx := context.Background()62 workingDir, err := os.Getwd()63 require.NoError(t, err)64 network, err := testcontainers.GenericNetwork(ctx, testcontainers.GenericNetworkRequest{65 NetworkRequest: testcontainers.NetworkRequest{Name: networkName},66 })67 require.NoError(t, err)68 defer network.Remove(ctx)69 var bindMounts map[string]string70 if test.chiconf != nil {71 bindMounts = map[string]string{72 fmt.Sprintf("%s/%s", workingDir, *test.chiconf): "/etc/clickhouse-server/config.d/testconf.xml",73 }74 } else {75 bindMounts = map[string]string{}76 }77 chReq := testcontainers.ContainerRequest{78 Image: clickHouseImage,79 ExposedPorts: []string{clickhousePort},80 WaitingFor: &clickhouseWaitStrategy{test: t, pollInterval: time.Millisecond * 200, startupTimeout: time.Minute},81 Networks: []string{networkName},82 Hostname: "chi",83 BindMounts: bindMounts,84 }85 chContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{86 ContainerRequest: chReq,87 Started: true,88 })89 require.NoError(t, err)90 defer chContainer.Terminate(ctx)91 jaegerContainers := make([]testcontainers.Container, 0)92 for _, pluginConfig := range test.configs {93 jaegerReq := testcontainers.ContainerRequest{94 Image: jaegerImage,95 ExposedPorts: []string{jaegerQueryPort, jaegerAdminPort},96 WaitingFor: wait.ForHTTP("/").WithPort(jaegerAdminPort).WithStartupTimeout(time.Second * 10),97 Env: map[string]string{98 "SPAN_STORAGE_TYPE": "grpc-plugin",99 },100 Cmd: []string{101 "--grpc-storage-plugin.binary=/project-dir/jaeger-clickhouse-linux-amd64",102 fmt.Sprintf("--grpc-storage-plugin.configuration-file=/project-dir/e2etests/%s", pluginConfig),103 "--grpc-storage-plugin.log-level=debug",104 },105 BindMounts: map[string]string{106 workingDir + "/..": "/project-dir",107 },108 Networks: []string{networkName},109 }110 // Call Start() manually here so that if it fails then we can still access the logs.111 jaegerContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{112 ContainerRequest: jaegerReq,113 })114 require.NoError(t, err)115 defer func() {116 logs, errLogs := jaegerContainer.Logs(ctx)117 require.NoError(t, errLogs)118 all, errLogs := ioutil.ReadAll(logs)119 require.NoError(t, errLogs)120 fmt.Printf("Jaeger logs:\n---->\n%s<----\n\n", string(all))121 jaegerContainer.Terminate(ctx)122 }()123 err = jaegerContainer.Start(ctx)124 require.NoError(t, err)125 jaegerContainers = append(jaegerContainers, jaegerContainer)126 }127 for _, jaegerContainer := range jaegerContainers {128 jaegerQueryPort, err := jaegerContainer.MappedPort(ctx, jaegerQueryPort)129 require.NoError(t, err)130 err = awaitility.Await(100*time.Millisecond, time.Second*3, func() bool {131 // Jaeger traces itself so this request generates some spans132 response, errHTTP := http.Get(fmt.Sprintf("http://localhost:%d/api/services", jaegerQueryPort.Int()))133 require.NoError(t, errHTTP)134 body, errHTTP := ioutil.ReadAll(response.Body)135 require.NoError(t, errHTTP)136 var r result137 errHTTP = json.Unmarshal(body, &r)138 require.NoError(t, errHTTP)139 return len(r.Data) == 1 && r.Data[0] == "jaeger-query"140 })141 assert.NoError(t, err)142 }143}144type result struct {145 Data []string `json:"data"`146}147type clickhouseWaitStrategy struct {148 test *testing.T149 pollInterval time.Duration150 startupTimeout time.Duration151}152var _ wait.Strategy = (*clickhouseWaitStrategy)(nil)153func (c *clickhouseWaitStrategy) WaitUntilReady(ctx context.Context, target wait.StrategyTarget) error {154 ctx, cancelContext := context.WithTimeout(ctx, c.startupTimeout)155 defer cancelContext()156 port, err := target.MappedPort(ctx, clickhousePort)157 require.NoError(c.test, err)158 db := clickhouse.OpenDB(&clickhouse.Options{159 Addr: []string{160 fmt.Sprintf("localhost:%d", port.Int()),161 },162 Auth: clickhouse.Auth{163 Database: "default",164 },165 Compression: &clickhouse.Compression{166 Method: clickhouse.CompressionLZ4,167 },168 })169 require.NoError(c.test, err)170 for {171 select {172 case <-ctx.Done():173 return ctx.Err()174 case <-time.After(c.pollInterval):175 if err := db.Ping(); err != nil {176 continue177 }178 return nil179 }180 }181}...

Full Screen

Full Screen

kafkacluster.go

Source:kafkacluster.go Github

copy

Full Screen

1package testcontainer2import (3 "context"4 "github.com/testcontainers/testcontainers-go"5 "io/ioutil"6 "os"7)8const (9 CLUSTER_NETWORK_NAME = "kafka-cluster"10 ZOOKEEPER_PORT = "2181"11 KAFKA_BROKER_PORT = "9092"12 KAFKA_CLIENT_PORT = "9093"13 ZOOKEEPER_IMAGE = "confluentinc/cp-zookeeper:5.2.1"14 KAFKA_IMAGE = "confluentinc/cp-kafka:5.2.1"15)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)68 zookeeperContainer := createZookeeperContainer(dockerNetwork)69 kafkaContainer := createKafkaContainer(dockerNetwork)70 return &KafkaCluster{71 zookeeperContainer: zookeeperContainer,72 kafkaContainer: kafkaContainer,73 }74}75func createZookeeperContainer(network *testcontainers.DockerNetwork) testcontainers.Container {76 ctx := context.Background()77 // creates the zookeeper container, but do not start it yet78 zookeeperContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{79 ContainerRequest: testcontainers.ContainerRequest{80 Image: ZOOKEEPER_IMAGE,81 ExposedPorts: []string{ZOOKEEPER_PORT},82 Env: map[string]string{"ZOOKEEPER_CLIENT_PORT": ZOOKEEPER_PORT, "ZOOKEEPER_TICK_TIME": "2000"},83 Networks: []string{network.Name},84 NetworkAliases: map[string][]string{network.Name: {"zookeeper"}},85 },86 })87 if err != nil {88 panic(err)89 }90 return zookeeperContainer91}92func createKafkaContainer(network *testcontainers.DockerNetwork) testcontainers.Container {93 ctx := context.Background()94 // creates the kafka container, but do not start it yet95 kafkaContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{96 ContainerRequest: testcontainers.ContainerRequest{97 Image: KAFKA_IMAGE,98 ExposedPorts: []string{KAFKA_CLIENT_PORT},99 Env: map[string]string{100 "KAFKA_BROKER_ID": "1",101 "KAFKA_ZOOKEEPER_CONNECT": "zookeeper:" + ZOOKEEPER_PORT,102 "KAFKA_LISTENERS": "PLAINTEXT://0.0.0.0:" + KAFKA_CLIENT_PORT + ",BROKER://0.0.0.0:" + KAFKA_BROKER_PORT,103 "KAFKA_LISTENER_SECURITY_PROTOCOL_MAP": "BROKER:PLAINTEXT,PLAINTEXT:PLAINTEXT",104 "KAFKA_INTER_BROKER_LISTENER_NAME": "BROKER",105 "KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR": "1",106 },107 Networks: []string{network.Name},108 NetworkAliases: map[string][]string{network.Name: {"kafka"}},109 // the container only starts when it finds and run /testcontainers_start.sh110 Cmd: []string{"sh", "-c", "while [ ! -f /testcontainers_start.sh ]; do sleep 0.1; done; /testcontainers_start.sh"},111 },112 })113 if err != nil {114 panic(err)115 }116 return kafkaContainer117}...

Full Screen

Full Screen

container.go

Source:container.go Github

copy

Full Screen

1package test2import (3 "context"4 "fmt"5 "github.com/testcontainers/testcontainers-go"6 "github.com/testcontainers/testcontainers-go/wait"7 "path/filepath"8)9type PostgresContainer struct {10 testcontainers.Container11 URI string12}13func NewPostgresContainer(ctx context.Context) (*PostgresContainer, error) {14 req := testcontainers.ContainerRequest{15 Image: "postgres:14.2",16 ExposedPorts: []string{"5432/tcp"},17 WaitingFor: wait.ForAll(18 wait.ForListeningPort("5432/tcp"),19 wait.ForLog("database system is ready to accept connections"),20 ),21 Env: map[string]string{22 "POSTGRES_DB": "postgres",23 "POSTGRES_USER": "postgres",24 "POSTGRES_PASSWORD": "postgres",25 },26 }27 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{28 ContainerRequest: req,29 Started: true,30 })31 if err != nil {32 return nil, err33 }34 addr, err := container.Endpoint(ctx, "")35 if err != nil {36 return nil, err37 }38 uri := fmt.Sprintf("postgres://postgres:postgres@%s/postgres?sslmode=disable", addr)39 return &PostgresContainer{40 Container: container,41 URI: uri,42 }, nil43}44type LocalstackContainer struct {45 testcontainers.Container46 Port string47}48func NewLocalstackContainer(ctx context.Context) (*LocalstackContainer, error) {49 setupPath, err := filepath.Abs("../../scripts/setup_localstack.sh")50 if err != nil {51 return nil, err52 }53 req := testcontainers.ContainerRequest{54 Image: "localstack/localstack:0.14.2",55 ExposedPorts: []string{"4566/tcp"},56 WaitingFor: wait.ForLog("Initialization has finished!"),57 Env: map[string]string{58 "DEFAULT_REGION": "us-east-2",59 "SERVICES": "ses,s3",60 "START_WEB": "0",61 },62 Mounts: testcontainers.Mounts(testcontainers.BindMount(setupPath, "/docker-entrypoint-initaws.d/init.sh")),63 }64 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{65 ContainerRequest: req,66 Started: true,67 })68 if err != nil {69 return nil, err70 }71 mappedPort, err := container.MappedPort(ctx, "4566")72 if err != nil {73 return nil, err74 }75 return &LocalstackContainer{76 Container: container,77 Port: mappedPort.Port(),78 }, nil79}...

Full Screen

Full Screen

Type

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 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/tcp")19 if err != nil {20 panic(err)21 }22 fmt.Printf("Redis is available at port %s:%s", ip, mappedPort.Port())23}24import (25func main() {26 ctx := context.Background()27 req := testcontainers.ContainerRequest{28 ExposedPorts: []string{"6379/tcp"},29 WaitingFor: wait.ForListeningPort("6379/tcp"),30 }31 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{32 })33 if err != nil {34 panic(err)35 }36 defer redis.Terminate(ctx)37 err = redis.Start(ctx)38 if err != nil {39 panic(err)40 }41 ip, err := redis.Host(ctx)42 if err != nil {43 panic(err)44 }45 mappedPort, err := redis.MappedPort(ctx, "6379/tcp")46 if err != nil {47 panic(err)48 }49 fmt.Printf("Redis is available at port %s:%s", ip, mappedPort.Port())50}51import (52func main() {53 ctx := context.Background()

Full Screen

Full Screen

Type

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 defer redis.Terminate(ctx)14 ip, err := redis.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := redis.MappedPort(ctx, "6379")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Printf("redis available on %s:%s\n", ip, port.Port())23}

Full Screen

Full Screen

Type

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 redisHost, err := redisContainer.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 redisPort, err := redisContainer.MappedPort(ctx, "6379/tcp")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Printf("Redis host: %s, port: %s", redisHost, redisPort.Port())23}

Full Screen

Full Screen

Type

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 nginxC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer nginxC.Terminate(ctx)14 ip, err := nginxC.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := nginxC.MappedPort(ctx, "80")19 if err != nil {20 panic(err)21 }22 if err != nil {23 panic(err)24 }25 fmt.Println(resp.Status)26}27import (28func main() {29 ctx := context.Background()30 req := testcontainers.ContainerRequest{31 ExposedPorts: []string{"80/tcp"},32 WaitingFor: wait.ForHTTP("/"),33 }34 nginxC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{35 })36 if err != nil {37 panic(err)38 }39 defer nginxC.Terminate(ctx)40 ip, err := nginxC.Host(ctx)41 if err != nil {42 panic(err)43 }44 port, err := nginxC.MappedPort(ctx, "80")45 if err != nil {46 panic(err)47 }

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 Cmd: []string{"sh", "-c", "while true; do echo hello world; sleep 1; done"},6 ExposedPorts: []string{"80/tcp"},7 WaitingFor: wait.ForLog("hello world"),8 }

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"6379/tcp"},5 WaitingFor: wait.ForListeningPort("6379/tcp"),6 }7 redisContainer, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{8 })9 if err != nil {10 panic(err)11 }12 defer redisContainer.Terminate(context.Background())13 ip, err := redisContainer.Host(context.Background())14 if err != nil {15 panic(err)16 }17 port, err := redisContainer.MappedPort(context.Background(), "6379")18 if err != nil {19 panic(err)20 }21 client := redis.NewClient(&redis.Options{22 Addr: fmt.Sprintf("%s:%s", ip, port.Port()),23 })24 err = client.Set(context.Background(), "foo", "bar", 0).Err()25 if err != nil {26 panic(err)27 }28 val, err := client.Get(context.Background(), "foo").Result()29 if err != nil {30 panic(err)31 }32 fmt.Println("foo", val)33}34import (35func main() {36 req := testcontainers.ContainerRequest{37 ExposedPorts: []string{"6379/tcp"},38 WaitingFor: wait.ForListeningPort("6379/tcp"),39 }40 redisContainer, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{41 })42 if err != nil {43 panic(err)44 }45 defer redisContainer.Terminate(context.Background())46 ip, err := redisContainer.Host(context.Background())47 if err != nil {48 panic(err)49 }

Full Screen

Full Screen

Type

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 req := testcontainers.ContainerRequest{4 ExposedPorts: []string{"6379/tcp"},5 WaitingFor: wait.ForListeningPort("6379/tcp"),6 }7 ctx := context.Background()8 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer redis.Terminate(ctx)14 port, err := redis.MappedPort(ctx, "6379/tcp")15 if err != nil {16 log.Fatal(err)17 }18 ip, err := redis.Host(ctx)19 if err != nil {20 log.Fatal(err)21 }22 fmt.Println(ip, port.Int())23 f, err := os.Create("redis.txt")24 if err != nil {25 panic(err)26 }27 f.WriteString(fmt.Sprint(ip, port.Int()))28 f.Close()29 time.Sleep(10 * time.Second)30}

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