Best Testcontainers-go code snippet using testcontainers.randomString
e2e_test.go
Source:e2e_test.go  
...29}30var params cliParams31func init() {32	flag.StringVar(¶ms.ImageName, "image", "livepeer/catalyst", "Docker image to use when loading container")33	flag.StringVar(¶ms.NetworkName, "network", randomString("catalyst-test-"), "Docker network name to use when starting")34}35func randomString(prefix string) string {36	const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"37	const length = 838	res := make([]byte, length)39	for i := 0; i < length; i++ {40		res[i] = charset[rand.Intn(length)]41	}42	return fmt.Sprintf("%s%s", prefix, string(res))43}44func TestMain(m *testing.M) {45	flag.Parse()46	os.Exit(m.Run())47}48type network struct {49	testcontainers.Network50	name string51}52type catalystContainer struct {53	testcontainers.Container54	webConsole   string55	serf         string56	http         string57	httpCatalyst string58	rtmp         string59	ip           string60	hostname     string61}62func (c *catalystContainer) Terminate(ctx context.Context) {63	c.StopLogProducer()64	c.Container.Terminate(ctx)65}66func TestMultiNodeCatalyst(t *testing.T) {67	if testing.Short() {68		t.Skip("skipping testing in short mode")69	}70	// given71	ctx, cancel := context.WithCancel(context.Background())72	defer cancel()73	network := createNetwork(ctx, t)74	defer network.Remove(ctx)75	h1 := randomString("catalyst-")76	h2 := randomString("catalyst-")77	// when78	c1 := startCatalyst(ctx, t, h1, network.name, defaultMistConfig(h1))79	defer c1.Terminate(ctx)80	c2 := startCatalyst(ctx, t, h2, network.name, mistConfigConnectTo(h2, h1))81	defer c2.Terminate(ctx)82	// then83	requireMembersJoined(t, c1, c2)84	p := startStream(t, c1)85	defer p.Kill()86	requireReplicatedStream(t, c2)87	requireStreamRedirection(t, c1, c2)88}89func createNetwork(ctx context.Context, t *testing.T) *network {90	name := params.NetworkName...container_test.go
Source:container_test.go  
...27}28func TestStartGenericContainer_Success(t *testing.T) {29	t.Parallel()30	c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{31		Name:  randomString(8),32		Image: "alpine",33	})34	require.NotNil(t, c)35	assert.NoError(t, err)36	defer c.Terminate(context.Background()) // nolint: errcheck37}38func TestStartGenericContainer_SuccessButCallbackError(t *testing.T) {39	t.Parallel()40	c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{41		Name:  randomString(8),42		Image: "alpine",43	}, testcontainers.WithCallback(func(context.Context, testcontainers.Container, testcontainers.ContainerRequest) error {44		return errors.New("callback error")45	}))46	require.NotNil(t, c)47	defer c.Terminate(context.Background()) // nolint: errcheck48	expected := errors.New("callback error")49	assert.Equal(t, expected, err)50}51func TestStartGenericContainer_NamePrefix(t *testing.T) {52	t.Parallel()53	prefix := randomString(8)54	c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{55		Name:  "test",56		Image: "alpine",57	}, testcontainers.WithNamePrefix(prefix))58	require.NotNil(t, c)59	assert.NoError(t, err)60	defer c.Terminate(context.Background()) // nolint: errcheck61	actual, err := c.Name(context.Background())62	expected := fmt.Sprintf("/%s_test", prefix)63	assert.Equal(t, expected, actual)64	assert.NoError(t, err)65}66func TestStartGenericContainer_NameSuffix(t *testing.T) {67	t.Parallel()68	suffix := randomString(8)69	c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{70		Name:  "test",71		Image: "alpine",72	}, testcontainers.WithNameSuffix(suffix))73	require.NotNil(t, c)74	assert.NoError(t, err)75	defer c.Terminate(context.Background()) // nolint: errcheck76	actual, err := c.Name(context.Background())77	expected := fmt.Sprintf("/test_%s", suffix)78	assert.Equal(t, expected, actual)79	assert.NoError(t, err)80}81func TestStartGenericContainer_NamePrefixAndSuffix(t *testing.T) {82	t.Parallel()83	prefix := randomString(8)84	suffix := randomString(8)85	c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{86		Name:  "test",87		Image: "alpine",88	}, testcontainers.WithNamePrefix(prefix), testcontainers.WithNameSuffix(suffix))89	require.NotNil(t, c)90	assert.NoError(t, err)91	defer c.Terminate(context.Background()) // nolint: errcheck92	actual, err := c.Name(context.Background())93	expected := fmt.Sprintf("/%s_test_%s", prefix, suffix)94	assert.Equal(t, expected, actual)95	assert.NoError(t, err)96}97func TestStartGenericContainer_WithImageName(t *testing.T) {98	t.Parallel()99	c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{100		Name:  randomString(8),101		Image: "alpine-unknown",102	}, testcontainers.WithImageName("alpine"))103	require.NotNil(t, c)104	assert.NoError(t, err)105	defer c.Terminate(context.Background()) // nolint: errcheck106}107func TestStartGenericContainer_WithImageTag(t *testing.T) {108	t.Parallel()109	c, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{110		Name:  randomString(8),111		Image: "alpine:unknown",112	}, testcontainers.WithImageTag("latest"))113	require.NotNil(t, c)114	assert.NoError(t, err)115	defer c.Terminate(context.Background()) // nolint: errcheck116}117func TestStartGenericContainers_Success(t *testing.T) {118	t.Parallel()119	containers, err := testcontainers.StartGenericContainers(context.Background(),120		testcontainers.StartGenericContainerRequest{121			Request: testcontainers.ContainerRequest{122				Name:         "postgres",123				Image:        "postgres:12-alpine",124				ExposedPorts: []string{":5432"},125				Env: map[string]string{126					"LC_ALL":            "C.UTF-8",127					"POSTGRES_DB":       "test",128					"POSTGRES_USER":     "test",129					"POSTGRES_PASSWORD": "test",130				},131				WaitingFor: wait.ForHealthCheckCmd("pg_isready").132					WithRetries(3).133					WithStartPeriod(time.Second).134					WithTestTimeout(5 * time.Second).135					WithTestInterval(10 * time.Second),136			},137			Options: []testcontainers.GenericContainerOption{138				testcontainers.WithNameSuffix(randomString(8)),139			},140		},141		testcontainers.StartGenericContainerRequest{142			Request: testcontainers.ContainerRequest{143				Name:  randomString(8),144				Image: "alpine",145			},146		},147	)148	assert.NoError(t, err)149	require.Len(t, containers, 2)150}151func TestStartGenericContainers_Error(t *testing.T) {152	t.Parallel()153	containers, err := testcontainers.StartGenericContainers(context.Background(),154		testcontainers.StartGenericContainerRequest{155			Request: testcontainers.ContainerRequest{156				Name: randomString(8),157			},158			Options: []testcontainers.GenericContainerOption{159				testcontainers.WithProviderType(-1),160			},161		},162		testcontainers.StartGenericContainerRequest{163			Request: testcontainers.ContainerRequest{164				Name: randomString(8),165			},166			Options: []testcontainers.GenericContainerOption{167				testcontainers.WithProviderType(-1),168			},169		},170		testcontainers.StartGenericContainerRequest{171			Request: testcontainers.ContainerRequest{172				Name:  randomString(8),173				Image: "alpine",174			},175		},176	)177	t.Logf("logs:\n%s", err.Error())178	require.NotEmpty(t, containers)179}180func TestStopGenericContainers_Success(t *testing.T) {181	t.Parallel()182	containers, err := testcontainers.StartGenericContainers(context.Background(),183		testcontainers.StartGenericContainerRequest{184			Request: testcontainers.ContainerRequest{185				Name:  randomString(8),186				Image: "alpine",187			},188		},189	)190	require.NotEmpty(t, containers)191	require.NoError(t, err)192	err = testcontainers.StopGenericContainers(context.Background(), containers...)193	assert.NoError(t, err)194}195func TestStopGenericContainers_Error(t *testing.T) {196	t.Parallel()197	containers, err := testcontainers.StartGenericContainers(context.Background(),198		testcontainers.StartGenericContainerRequest{199			Request: testcontainers.ContainerRequest{200				Name:  randomString(8),201				Image: "alpine",202			},203		},204	)205	require.NotEmpty(t, containers)206	require.NoError(t, err)207	_ = containers[0].Terminate(context.Background()) // nolint: errcheck208	err = testcontainers.StopGenericContainers(context.Background(), containers...)209	require.Error(t, err)210	t.Logf("logs:\n%s", err.Error())211}212// nolint: unparam213func randomString(length int) string {214	var rngSeed int64215	_ = binary.Read(crand.Reader, binary.LittleEndian, &rngSeed) // nolint: errcheck216	r := rand.New(rand.NewSource(rngSeed))                       // nolint: gosec217	result := make([]byte, length/2)218	_, _ = r.Read(result)219	return hex.EncodeToString(result)220}...helper_test.go
Source:helper_test.go  
1package harego_test2import (3	"context"4	"fmt"5	"io"6	"math/rand"7	"net/http"8	"os"9	"strconv"10	"strings"11	"testing"12	"time"13	"github.com/blokur/harego"14	"github.com/blokur/harego/internal"15	"github.com/blokur/testament"16	"github.com/spf13/viper"17	"github.com/stretchr/testify/assert"18	"github.com/stretchr/testify/require"19	"github.com/testcontainers/testcontainers-go"20	"github.com/testcontainers/testcontainers-go/wait"21)22func init() {23	viper.AutomaticEnv()24	rand.Seed(time.Now().UnixNano())25	internal.RabbitMQAddr = viper.GetString(internal.RabbitMQAddrName)26	internal.RabbitMQUser = viper.GetString(internal.RabbitMQUserName)27	internal.RabbitMQPass = viper.GetString(internal.RabbitMQPassName)28	internal.RabbitMQVirtual = viper.GetString(internal.RabbitMQVirtualName)29}30func randomBody(lines int) string {31	body := make([]string, lines)32	for i := range body {33		body[i] = testament.RandomString(rand.Intn(100) + 10)34	}35	return strings.Join(body, "\n")36}37// getClient creates a client without a queue if the queueName is empty.38func getClient(t *testing.T, queueName string, conf ...harego.ConfigFunc) *harego.Client {39	t.Helper()40	exchange := "test." + testament.RandomString(20)41	vh := "test." + testament.RandomString(20)42	return getNamedClient(t, vh, exchange, queueName, conf...)43}44// getNamedClient creates a client without a queue if the queueName is empty.45func getNamedClient(t *testing.T, vh, exchange, queueName string, conf ...harego.ConfigFunc) *harego.Client {46	t.Helper()47	var (48		adminURL string49		err      error50	)51	apiAddress := strings.Split(internal.RabbitMQAddr, ":")[0]52	adminPort := 1567253	if v, ok := os.LookupEnv("RABBITMQ_ADMIN_PORT"); ok {54		adminPort, err = strconv.Atoi(v)55		if err != nil {56			adminPort = 1567257		}58	}59	if vh != "" {60		adminURL = fmt.Sprintf("http://%s:%d/api/vhosts/%s", apiAddress, adminPort, vh)61		req, err := http.NewRequest("PUT", adminURL, http.NoBody)62		require.NoError(t, err)63		req.SetBasicAuth(internal.RabbitMQUser, internal.RabbitMQPass)64		resp, err := http.DefaultClient.Do(req)65		if resp != nil && resp.Body != nil {66			defer func() {67				io.Copy(io.Discard, resp.Body)68				resp.Body.Close()69			}()70		}71		require.NoError(t, err)72	}73	url := fmt.Sprintf("amqp://%s:%s@%s/%s", internal.RabbitMQUser, internal.RabbitMQPass, internal.RabbitMQAddr, vh)74	conf = append([]harego.ConfigFunc{75		harego.ExchangeName(exchange),76		harego.QueueName(queueName),77	}, conf...)78	e, err := harego.NewClient(harego.URLConnector(url),79		conf...,80	)81	require.NoError(t, err)82	t.Cleanup(func() {83		assert.Eventually(t, func() bool {84			e.Close()85			return true86		}, 2*time.Second, 10*time.Millisecond)87		urls := []string{88			fmt.Sprintf("http://%s:%d/api/exchanges/%s", apiAddress, adminPort, exchange),89		}90		if queueName != "" {91			urls = append(urls,92				fmt.Sprintf("http://%s:%d/api/queues/%s", apiAddress, adminPort, queueName),93			)94		}95		if vh != "" {96			urls = append(urls, adminURL)97		}98		for _, url := range urls {99			func() {100				req, err := http.NewRequest("DELETE", url, http.NoBody)101				require.NoError(t, err)102				req.SetBasicAuth(internal.RabbitMQUser, internal.RabbitMQPass)103				resp, err := http.DefaultClient.Do(req)104				if resp != nil && resp.Body != nil {105					defer func() {106						io.Copy(io.Discard, resp.Body)107						resp.Body.Close()108					}()109				}110				require.NoError(t, err)111			}()112		}113	})114	return e115}116// getContainer returns a new container running rabbimq that is ready for117// accepting connections.118func getContainer(t *testing.T) (container testcontainers.Container, addr string) {119	t.Helper()120	ctx := context.Background()121	req := testcontainers.ContainerRequest{122		Image:        "rabbitmq:3.8.19-management-alpine",123		ExposedPorts: []string{"5672/tcp", "15672/tcp"},124		WaitingFor:   wait.ForListeningPort("5672/tcp"),125	}126	container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{127		ContainerRequest: req,128		Started:          true,129	})130	require.NoError(t, err)131	ip, err := container.Host(ctx)132	require.NoError(t, err)133	port, err := container.MappedPort(ctx, "5672")134	require.NoError(t, err)135	t.Cleanup(func() {136		container.Terminate(ctx)137	})138	return container, fmt.Sprintf("amqp://%s:%s/", ip, port.Port())139}140// restartRabbitMQ restarts the rabbitmq server inside the container.141func restartRabbitMQ(t *testing.T, container testcontainers.Container) {142	t.Helper()143	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)144	defer cancel()145	_, err := container.Exec(ctx, []string{146		"rabbitmqctl",147		"stop_app",148	})149	require.NoError(t, err)150	go func() {151		ctx, cancel := context.WithTimeout(context.Background(), time.Minute)152		defer cancel()153		container.Exec(ctx, []string{154			"rabbitmqctl",155			"start_app",156		})157	}()158}...randomString
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	redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9	})10	if err != nil {11		panic(err)12	}13	defer redisContainer.Terminate(ctx)14	ip, err := redisContainer.Host(ctx)15	if err != nil {16		panic(err)17	}18	port, err := redisContainer.MappedPort(ctx, "6379/tcp")19	if err != nil {20		panic(err)21	}22	redisClient := redis.NewClient(&redis.Options{23		Addr:     fmt.Sprintf("%s:%s", ip, port.Port()),24	})25	pong, err := redisClient.Ping().Result()26	if err != nil {27		panic(err)28	}29	fmt.Println(pong)30}randomString
Using AI Code Generation
1import (2func main() {3    randomString := testcontainers.RandomString(10)4    fmt.Println(randomString)5}6import (7func main() {8    randomString := testcontainers.RandomString(10)9    fmt.Println(randomString)10}11import (12func main() {13    randomString := testcontainers.RandomString(10)14    fmt.Println(randomString)15}16import (17func main() {18    randomString := testcontainers.RandomString(10)19    fmt.Println(randomString)20}21import (22func main() {23    randomString := testcontainers.RandomString(10)24    fmt.Println(randomString)25}26import (27func main() {28    randomString := testcontainers.RandomString(10)29    fmt.Println(randomString)30}31import (32func main() {33    randomString := testcontainers.RandomString(10)34    fmt.Println(randomString)35}36import (37func main() {38    randomString := testcontainers.RandomString(10)39    fmt.Println(randomString)40}41import (randomString
Using AI Code Generation
1import (2func main() {3    randomString := testcontainers.RandomString(10)4    fmt.Println("Random string: ", randomString)5}6import (7func main() {8    rand.Seed(time.Now().UnixNano())9    var seededRand *rand.Rand = rand.New(10        rand.NewSource(time.Now().UnixNano()))11    b := make([]byte, 10)12    for i := range b {13        b[i] = charset[seededRand.Intn(len(charset))]14    }15    fmt.Println(string(b))16}17import (18func main() {19    rand.Seed(time.Now().UnixNano())20    fmt.Println(rand.Intn(100))21}22import (23func main() {24    rand.Seed(time.Now().UnixNano())25    fmt.Println(rand.Intn(100-50) + 50)26}27import (28func main() {29    rand.Seed(time.Now().UnixNano())30    fmt.Println(rand.Float64())31}randomString
Using AI Code Generation
1import (2func main() {3    client, err := docker.NewClientFromEnv()4    if err != nil {5        log.Fatal(err)6    }7    pool, err := dockertest.NewPool("")8    if err != nil {9        log.Fatal(err)10    }11    resource, err := pool.RunWithOptions(&dockertest.RunOptions{12        Cmd:        []string{"sleep", "3600"},13    })14    if err != nil {15        log.Fatalf("Could not start resource: %s", err)16    }17    if err := pool.Retry(func() error {18        client, err = docker.NewClientFromEnv()19        if err != nil {20        }21        return client.Ping()22    }); err != nil {23        log.Fatalf("Could not connect to docker: %s", err)24    }25    if err := pool.Purge(resource); err != nil {26        log.Fatalf("Could not purge resource: %s", err)27    }28    randomString := randomstring.RandomString(10)29    file, err := os.Create(randomString)30    if err != nil {31        log.Fatalf("Could not create file: %s", err)32    }33    defer file.Close()34    time.Sleep(10 * time.Second)35    fmt.Println("Done")36}37import (randomString
Using AI Code Generation
1import (2func main() {3    fmt.Println(testcontainers.RandString(10))4}5import (6func main() {7    ctx := context.Background()8    req := testcontainers.ContainerRequest{9        ExposedPorts: []string{"6379/tcp"},10        WaitingFor:   wait.ForListeningPort("6379/tcp"),11    }12    redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{13    })14    if err != nil {15        panic(err)16    }17    defer redisContainer.Terminate(ctx)18    redisHost, err := redisContainer.Host(ctx)19    if err != nil {20        panic(err)21    }22    redisPort, err := redisContainer.MappedPort(ctx, "6379/tcp")23    if err != nil {24        panic(err)25    }26    fmt.Println(redisHost, redisPort.Int())27}randomString
Using AI Code Generation
1import (2func main() {3	fmt.Println(testcontainers.RandomString(10))4}5import "github.com/testcontainers/testcontainers-go"6ctx := context.Background()7req := testcontainers.ContainerRequest{8	ExposedPorts: []string{"80/tcp"},9	Cmd:          []string{"echo", "hello world"},10	WaitingFor:   wait.ForLog("hello world"),11}12container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{13})14err = container.Start(ctx)15ip, err := container.Host(ctx)16port, err := container.MappedPort(ctx, "80")17id, err := container.ContainerID(ctx)18err = container.Terminate(ctx)19err = container.Remove(ctx)20import (21func main() {22	ctx := context.Background()23	req := testcontainers.ContainerRequest{24		ExposedPorts: []string{"80/tcp"},25		Cmd:          []string{"echo", "hello world"},26		WaitingFor:   wait.ForLog("hello world"),27	}28	container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{randomString
Using AI Code Generation
1import (2func main() {3	fmt.Println(testcontainers.RandomString(10))4}5import (6func main() {7	fmt.Println(testcontainers.RandomString(10))8}9import (10func main() {11	fmt.Println(testcontainers.RandomString(10))12}13import (14func main() {15	fmt.Println(testcontainers.RandomString(10))16}17import (18func main() {19	fmt.Println(testcontainers.RandomString(10))20}21import (22func main() {23	fmt.Println(testcontainers.RandomString(10))24}25import (26func main() {27	fmt.Println(testcontainers.RandomString(10))28}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!!
