Best Testcontainers-go code snippet using testcontainers.reaperImage
testcontainer.go
Source:testcontainer.go
1package testcontainer2import (3 "context"4 "encoding/base64"5 "encoding/json"6 "fmt"7 "io"8 "os"9 "sync"10 "github.com/docker/docker/api/types"11 "github.com/docker/docker/client"12 "github.com/testcontainers/testcontainers-go"13 "github.com/testcontainers/testcontainers-go/wait"14)15// Type Aliasing for reduce code line size. Remove external deps from other places too.16type (17 Container = testcontainers.Container18 ContainerRequest = testcontainers.ContainerRequest19 ContainerFile = testcontainers.ContainerFile20 Network = testcontainers.Network21 DockerNetwork = testcontainers.DockerNetwork22 NetworkRequest = testcontainers.NetworkRequest23 GenericContainerRequest = testcontainers.GenericContainerRequest24 GenericNetworkRequest = testcontainers.GenericNetworkRequest25)26// Func aliasing - for reduce code line size. Remove external deps from other places too.27var (28 GenericContainer = testcontainers.GenericContainer29 GenericNetwork = testcontainers.GenericNetwork30 Mounts = testcontainers.Mounts31 BindMount = testcontainers.BindMount32)33// BaseContainerConfig - base container request config.34type BaseContainerConfig struct {35 Name string // Hostname, ContainerName, Network alias36 Image string37 Port string38 Files []ContainerFile39 Binds []string40 Envs map[string]string41 Cmd []string42 ExposedPorts []string43 AutoRemove bool44 WaitingForStrategy wait.Strategy45}46// IsSkipReaperImage - is skip usage Reaper Image.47const IsSkipReaperImage = false // not skip usage reaper image on CI48// ReaperImage - is very important to re-define because by default testcontainers lib use reaper image based on docker.io ->49// https://github.com/testcontainers/testcontainers-go/blob/6ba6e7a0e4b0046507c28e24946d595a65a96dbf/reaper.go#L2450const ReaperImage = "" // use standard Reaper Image.51// NoUseAuth - not used any docker auth.52const NoUseAuth = ""53// RegistryTokenEnv - env with docker registry token from dp.54const RegistryTokenEnv = "" // not use any docker registry token for docker demon.55var (56 once sync.Once57 authRegistryCredStr string58)59type (60 Terminated interface {61 Terminate(ctx context.Context) error62 }63)64func TerminateIfNotNil(ctx context.Context, container Terminated) error {65 if container == nil {66 return nil67 }68 return container.Terminate(ctx)69}70// GetAuthRegistryCredStr - return auth encoded string for docker registry.71func GetAuthRegistryCredStr() string {72 registryToken := os.Getenv(RegistryTokenEnv)73 if registryToken == "" {74 return NoUseAuth75 }76 once.Do(func() {77 authRegistryCredStr = getAuthRegistryCredStr(registryToken)78 })79 return authRegistryCredStr80}81// getAuthRegistryCredStr - convert registry token to auth registry cred str in base64 format.82func getAuthRegistryCredStr(registryToken string) string {83 mustMarshalFunc := func(s interface{}) []byte {84 b, err := json.Marshal(s)85 if err != nil {86 panic(err)87 }88 return b89 }90 return base64.URLEncoding.EncodeToString(91 mustMarshalFunc(92 &types.AuthConfig{93 RegistryToken: registryToken,94 }))95}96// PullDockerImage - pull docker image via docker client.97func PullDockerImage(ctx context.Context, imageName string) error {98 if GetAuthRegistryCredStr() == "" {99 fmt.Println("WARN! `AuthRegistryCredStr` is empty. NOT FORCE PULL ANY IMAGES.")100 return nil101 }102 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())103 if err != nil {104 return fmt.Errorf("could not create docker client with custom not pull image: %s; err: %w",105 imageName, err)106 }107 out, err := cli.ImagePull(ctx, imageName, types.ImagePullOptions{RegistryAuth: GetAuthRegistryCredStr()})108 if err != nil {109 return fmt.Errorf("could not pull image: %s; err: %w", imageName, err)110 }111 defer func() { _ = out.Close() }()112 _, _ = io.Copy(os.Stdout, out)113 return nil114}115// NewGenericContainer - create new generic container with BaseContainerConfig and DockerNetwork.116func NewGenericContainer(ctx context.Context, cfg BaseContainerConfig, dockerNetwork *DockerNetwork) (Container, error) {117 return GenericContainer(ctx, GenericContainerRequest{118 ContainerRequest: GetBaseContainerRequest(cfg, dockerNetwork),119 })120}121// GetBaseContainerRequest - return base ContainerRequest.122func GetBaseContainerRequest(123 cfg BaseContainerConfig,124 dockerNetwork *DockerNetwork,125) ContainerRequest {126 return ContainerRequest{127 Name: cfg.Name,128 ReaperImage: ReaperImage,129 SkipReaper: IsSkipReaperImage,130 RegistryCred: GetAuthRegistryCredStr(),131 Hostname: cfg.Name,132 Image: cfg.Image,133 ExposedPorts: cfg.ExposedPorts,134 Env: cfg.Envs,135 Files: cfg.Files,136 Binds: cfg.Binds,137 Cmd: cfg.Cmd,138 Networks: []string{dockerNetwork.Name},139 NetworkAliases: map[string][]string{dockerNetwork.Name: {cfg.Name}},140 AutoRemove: cfg.AutoRemove,141 WaitingFor: cfg.WaitingForStrategy,142 }143}...
full_suite.go
Source:full_suite.go
1package suites2import (3 "context"4 "github.com/hiteshpattanayak-tw/ports_processor/test/suites/constants"5 "sync"6 "github.com/docker/go-connections/nat"7 "github.com/google/uuid"8 "github.com/stretchr/testify/suite"9 "github.com/testcontainers/testcontainers-go"10)11type SuiteId int12const (13 PostgresSuiteId SuiteId = iota14)15const postgresDBName = "test_db"16type IntegrationSuite interface {17 suite.TestingSuite18 suite.SetupAllSuite19 suite.TearDownAllSuite20 GetContainerHost() string21 GetContainerMappedPort() nat.Port22 SetCtx(ctx context.Context)23 SetNetwork(network *testcontainers.DockerNetwork)24 SetRootDir(rootDir string)25}26type FullSuiteConfig struct {27 RootDir string28 EnablePostgres bool29 PathToDbScripts string30 PostgresDBName string31 DisablePgBindMount bool32}33type FullSuite struct {34 suite.Suite35 Ctx context.Context36 Config FullSuiteConfig37 Network *testcontainers.DockerNetwork38 Suites map[SuiteId]IntegrationSuite39}40func NewFullSuite(config FullSuiteConfig) FullSuite {41 return FullSuite{Config: config}42}43func (f *FullSuite) SetupSuite() {44 var err error45 f.Ctx = context.Background()46 f.Network, err = CreateNetwork(f.Ctx, uuid.NewString())47 f.Require().NoError(err)48 f.Suites = make(map[SuiteId]IntegrationSuite)49 f.addSuiteIfEnabled(f.Config.EnablePostgres, PostgresSuiteId, &PostgresSuite{50 PathToScripts: f.Config.PathToDbScripts,51 DBName: postgresDBName,52 })53 var wg sync.WaitGroup54 for _, intSuite := range f.Suites {55 wg.Add(1)56 is := intSuite57 go func() {58 defer wg.Done()59 is.SetCtx(f.Ctx)60 is.SetT(f.T())61 is.SetNetwork(f.Network)62 is.SetRootDir(f.Config.RootDir)63 is.SetupSuite()64 }()65 }66 wg.Wait()67}68func (f *FullSuite) TearDownSuite() {69 for _, testSuite := range f.Suites {70 testSuite.TearDownSuite()71 }72 if f.Network != nil {73 _ = f.Network.Remove(f.Ctx)74 }75}76func (f *FullSuite) addSuiteIfEnabled(enabled bool, id SuiteId, suite IntegrationSuite) {77 if enabled {78 f.Suites[id] = suite79 }80}81func CreateNetwork(ctx context.Context, clusterNetworkName string) (*testcontainers.DockerNetwork, error) {82 network, err := testcontainers.GenericNetwork(ctx, testcontainers.GenericNetworkRequest{83 NetworkRequest: testcontainers.NetworkRequest{Name: clusterNetworkName, ReaperImage: constants.ReaperImage},84 })85 if err != nil {86 return nil, err87 }88 return network.(*testcontainers.DockerNetwork), nil89}...
base_suite.go
Source:base_suite.go
1package suites2import (3 "context"4 "github.com/docker/go-connections/nat"5 "github.com/hiteshpattanayak-tw/ports_processor/test/suites/constants"6 "github.com/stretchr/testify/suite"7 "github.com/testcontainers/testcontainers-go"8)9type BaseSuite struct {10 suite.Suite11 ctx context.Context12 network *testcontainers.DockerNetwork13 container testcontainers.Container14 rootDir string15}16func (s *BaseSuite) GetContainerHost() string {17 host, err := s.container.Host(s.ctx)18 s.Require().NoError(err)19 return host20}21func (s *BaseSuite) GetContainerMappedPort(portStr string) nat.Port {22 port, err := s.container.MappedPort(s.ctx, nat.Port(portStr))23 s.Require().NoError(err)24 return port25}26func (s *BaseSuite) SetCtx(ctx context.Context) {27 s.ctx = ctx28}29func (s *BaseSuite) SetNetwork(network *testcontainers.DockerNetwork) {30 s.network = network31}32func (s *BaseSuite) SetRootDir(rootDir string) {33 s.rootDir = rootDir34}35func (s *BaseSuite) TearDownSuite() {36 s.TerminateContainer(s.container)37}38func (s *BaseSuite) TerminateContainer(container testcontainers.Container) {39 if container != nil {40 if err := container.Terminate(s.ctx); err != nil {41 s.Require().NoError(err)42 }43 }44}45func (s *BaseSuite) GenericContainer(request testcontainers.GenericContainerRequest) (testcontainers.Container, error) {46 request.ReaperImage = constants.ReaperImage47 return testcontainers.GenericContainer(s.ctx, request)48}...
reaperImage
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 Cmd: []string{"echo", "hello world"},6 ExposedPorts: []string{"8080/tcp"},7 WaitingFor: wait.ForLog("hello world"),8 }9 reaper, err := testcontainers.Reaper(ctx, testcontainers.ReaperOptions{})10 if err != nil {11 log.Fatalf("Could not start reaper: %s", err)12 }13 defer reaper.Stop(ctx)14 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{15 })16 if err != nil {17 log.Fatalf("Could not start container: %s", err)18 }19 defer container.Terminate(ctx)20 ip, err := container.Host(ctx)21 if err != nil {22 log.Fatalf("Could not get container IP: %s", err)23 }24 port, err := container.MappedPort(ctx, "8080")25 if err != nil {26 log.Fatalf("Could not get container port: %s", err)27 }28 fmt.Printf("Container is listening on %s:%s", ip, port.Port())29}
reaperImage
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 WaitingFor: wait.ForLog("Reaper listening on port 80"),7 }8 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 ip, err := container.Host(ctx)14 if err != nil {15 log.Fatal(err)16 }17 port, err := container.MappedPort(ctx, "80")18 if err != nil {19 log.Fatal(err)20 }21 fmt.Printf("Started container with IP: %s and port: %s", ip, port.Port())22 err = container.Terminate(ctx)23 if err != nil {24 log.Fatal(err)25 }26}
reaperImage
Using AI Code Generation
1import (2func TestReaperImage(t *testing.T) {3 ctx := context.Background()4 cli, err := client.NewClientWithOpts(client.FromEnv)5 if err != nil {6 panic(err)7 }8 reaperImage, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 ContainerRequest: testcontainers.ContainerRequest{10 ExposedPorts: []string{"8080/tcp"},11 WaitingFor: wait.ForListeningPort("8080/tcp"),12 },13 })14 if err != nil {15 log.Fatalf("Could not start resource: %s", err)16 }17 reaperImageId, err := reaperImage.ContainerID(ctx)18 if err != nil {19 log.Fatalf("Could not get container ID: %s", err)20 }21 reaperImageName, err := reaperImage.Name(ctx)22 if err != nil {23 log.Fatalf("Could not get container name: %s", err)24 }25 reaperImageIP, err := reaperImage.Host(ctx)26 if err != nil {27 log.Fatalf("Could not get container IP: %s", err)28 }29 reaperImagePort, err := reaperImage.MappedPort(ctx, "8080/tcp")30 if err != nil {31 log.Fatalf("Could not get container port: %s", err)32 }33 reaperImageState, err := reaperImage.State(ctx)34 if err != nil {35 log.Fatalf("Could not get container state: %s", err)36 }37 reaperImageStatus, err := reaperImage.Status(ctx)38 if err != nil {39 log.Fatalf("Could not get container status: %s", err)40 }41 reaperImageLabels, err := reaperImage.Labels(ctx)
reaperImage
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello World")4 ctx := context.Background()5 req := testcontainers.ContainerRequest{6 Cmd: []string{"echo", "Hello World"},7 ExposedPorts: []string{"80/tcp"},8 WaitingFor: wait.ForLog("Hello World"),9 }10 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{11 })12 if err != nil {13 panic(err)14 }15 defer c.Terminate(ctx)16}17import (18func main() {19 fmt.Println("Hello World")20 ctx := context.Background()21 req := testcontainers.ContainerRequest{22 Cmd: []string{"echo", "Hello World"},23 ExposedPorts: []string{"80/tcp"},24 WaitingFor: wait.ForLog("Hello World"),25 }
reaperImage
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 }6 ryukContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{7 })8 if err != nil {9 panic(err)10 }11 host, err := ryukContainer.Host(ctx)12 if err != nil {13 panic(err)14 }15 port, err := ryukContainer.MappedPort(ctx, "8080/tcp")16 if err != nil {17 panic(err)18 }19 ryukClient := testcontainers.NewRyukClient(ryukURL)20 ryukClient.Connect()21 defer ryukClient.Stop()22 ryukClient.NotifyAboutContainerStop(ctx, containerID)23}24import (25func main() {26 ctx := context.Background()27 req := testcontainers.ContainerRequest{28 }
reaperImage
Using AI Code Generation
1func main() {2 ctx := context.Background()3 req := testcontainers.ContainerRequest{4 Cmd: []string{"sleep", "1m"},5 }6 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{7 })8 if err != nil {9 log.Fatal(err)10 }11 defer container.Terminate(ctx)12 ip, err := container.Host(ctx)13 if err != nil {14 log.Fatal(err)15 }16 port, err := container.MappedPort(ctx, "80")17 if err != nil {18 log.Fatal(err)19 }20 fmt.Printf("Container %s is listening on %s:%s", container.GetContainerID(), ip, port.Port())21}22func main() {23 ctx := context.Background()24 req := testcontainers.ContainerRequest{25 Cmd: []string{"sleep", "1m"},26 }27 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{28 })29 if err != nil {30 log.Fatal(err)31 }32 defer container.Terminate(ctx)33 ip, err := container.Host(ctx)34 if err != nil {35 log.Fatal(err)36 }37 port, err := container.MappedPort(ctx, "80")38 if err != nil {39 log.Fatal(err)40 }41 fmt.Printf("Container %s is listening on %s:%s", container.GetContainerID(), ip, port.Port())42}43func main() {44 ctx := context.Background()45 req := testcontainers.ContainerRequest{46 Cmd: []string{"sleep", "1m"},47 }48 container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{49 })50 if err != nil {
reaperImage
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 Cmd: []string{"top"},7 }
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!!