Best Testcontainers-go code snippet using testcontainers.Up
extmetric_test.go
Source:extmetric_test.go
1// SPDX-License-Identifier: MIT2// SPDX-FileCopyrightText: 2022 Steadybit GmbH3package extmetric4import (5 "context"6 "encoding/json"7 "fmt"8 "github.com/steadybit/action-kit/go/action_kit_api/v2"9 extension_kit "github.com/steadybit/extension-kit"10 "github.com/steadybit/extension-kit/extutil"11 "github.com/steadybit/extension-prometheus/extinstance"12 "github.com/stretchr/testify/assert"13 "github.com/stretchr/testify/require"14 "github.com/testcontainers/testcontainers-go"15 "github.com/testcontainers/testcontainers-go/wait"16 "os"17 "path"18 "testing"19 "time"20)21func TestQueryMetrics(t *testing.T) {22 // Given23 container, err := setupTestContainers(context.Background())24 require.Nil(t, err)25 instance := extinstance.Instance{Name: "test-prom", BaseUrl: container.baseUrl}26 extinstance.Instances = []extinstance.Instance{instance}27 require.Eventually(t, func() bool {28 result, err := getTestMetric(instance)29 return err == nil && len(*result.Metrics) > 030 }, time.Minute, time.Millisecond*200)31 // When32 result, exterr := getTestMetric(instance)33 require.Nil(t, exterr)34 assert.Len(t, *result.Metrics, 1)35 metric := (*result.Metrics)[0]36 assert.NotNil(t, metric.Timestamp)37 assert.Nil(t, metric.Name)38 assert.Equal(t, float64(1), metric.Value)39 assert.Equal(t, "up", metric.Metric["__name__"])40 assert.Equal(t, "localhost:9090", metric.Metric["instance"])41 assert.Equal(t, "prometheus", metric.Metric["job"])42}43func getTestMetric(instance extinstance.Instance) (*action_kit_api.QueryMetricsResult, *extension_kit.ExtensionError) {44 timestamp := time.Now()45 json, _ := json.Marshal(action_kit_api.QueryMetricsRequestBody{46 Target: extutil.Ptr(action_kit_api.Target{47 Name: instance.Name,48 }),49 Timestamp: timestamp,50 Config: map[string]interface{}{51 "query": "up",52 },53 })54 return Query(json)55}56type testContainer struct {57 container *testcontainers.Container58 baseUrl string59}60func setupTestContainers(ctx context.Context) (*testContainer, error) {61 wd, err := os.Getwd()62 if err != nil {63 return nil, err64 }65 containerReq := testcontainers.ContainerRequest{66 Image: "prom/prometheus:v2.38.0",67 Name: "test-prometheus",68 ExposedPorts: []string{"9090/tcp"},69 WaitingFor: wait.ForHTTP("/-/ready").WithPort("9090"),70 Mounts: testcontainers.ContainerMounts{71 testcontainers.ContainerMount{72 Source: testcontainers.GenericBindMountSource{73 HostPath: path.Join(wd, "prometheus-test-config"),74 },75 Target: "/etc/prometheus",76 ReadOnly: true,77 },78 },79 }80 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{81 ContainerRequest: containerReq,82 Started: true,83 })84 if err != nil {85 return nil, err86 }87 ip, err := container.Host(ctx)88 if err != nil {89 return nil, err90 }91 port, err := container.MappedPort(ctx, "9090")92 if err != nil {93 return nil, err94 }95 origin := fmt.Sprintf("http://%s:%s", ip, port.Port())96 return &testContainer{97 container: &container,98 baseUrl: origin,99 }, nil100}...
postgres_container.go
Source:postgres_container.go
...25 return PostgresContainer{26 Container: nil,27 }28}29// Up create a new postgres container with the connections params30func (c PostgresContainer) Up() PostgresConnection {31 containerRequest := testcontainers.ContainerRequest{32 Image: "postgres",33 ExposedPorts: []string{fmt.Sprintf("%s/tcp", postgresPort)},34 WaitingFor: wait.ForListeningPort(postgresPort),35 Env: map[string]string{36 "POSTGRES_USER": postgresUser,37 "POSTGRES_PASSWORD": postgresPassword,38 "POSTGRES_DB": postgresDatabase,39 },40 }41 container, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{42 ContainerRequest: containerRequest,43 Started: true,44 })...
redis_container.go
Source:redis_container.go
...20 return RedisContainer{21 Container: nil,22 }23}24// Up create a new redis container with the connections params25func (c RedisContainer) Up() RedisConnection {26 containerRequest := testcontainers.ContainerRequest{27 Image: "redis",28 ExposedPorts: []string{fmt.Sprintf("%s/tcp", redisPort)},29 WaitingFor: wait.ForListeningPort(redisPort),30 }31 container, err := testcontainers.GenericContainer(context.Background(), testcontainers.GenericContainerRequest{32 ContainerRequest: containerRequest,33 Started: true,34 })35 if err != nil {36 panic(err)37 }38 c.Container = container39 containerHost, _ := container.Host(context.Background())...
Up
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 panic(err)12 }13 defer mysqlContainer.Terminate(ctx)14 ip, err := mysqlContainer.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := mysqlContainer.MappedPort(ctx, "3306/tcp")19 if err != nil {20 panic(err)21 }22 fmt.Printf("host = %s, port = %s23", ip, port.Port())24}
Up
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 log.Fatal(err)12 }13 ip, err := postgresContainer.Host(ctx)14 if err != nil {15 log.Fatal(err)16 }17 mappedPort, err := postgresContainer.MappedPort(ctx, "5432")18 if err != nil {19 log.Fatal(err)20 }21 fmt.Println(ip, mappedPort.Int())22}
Up
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"3306/tcp"},6 WaitingFor: wait.ForLog("port: 3306 MySQL Community Server - GPL"),7 }8 mysqlContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatalf("Could not start container: %v", err)12 }13 defer mysqlContainer.Terminate(ctx)14 ip, err := mysqlContainer.Host(ctx)15 if err != nil {16 log.Fatalf("Could not get container IP: %v", err)17 }18 mappedPort, err := mysqlContainer.MappedPort(ctx, "3306")19 if err != nil {20 log.Fatalf("Could not get container mapped port: %v", err)21 }22 log.Printf("MySQL is available on %s:%s", ip, mappedPort.Port())
Up
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 redisHost, _ := redisContainer.Host(ctx)15 redisPort, _ := redisContainer.MappedPort(ctx, "6379")16 fmt.Println(redisHost, redisPort.Int())17}
Up
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 nginx, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer nginx.Terminate(ctx)14 ip, err := nginx.GetContainerIpAddress(ctx)15 if err != nil {16 panic(err)17 }18 fmt.Println("IP address of the container is", ip)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!!