Best Testcontainers-go code snippet using testcontainers.NewDockerCompose
compose_api_test.go
Source:compose_api_test.go
...8 "github.com/stretchr/testify/assert"9 "github.com/testcontainers/testcontainers-go/wait"10)11func TestDockerComposeAPI(t *testing.T) {12 compose, err := NewDockerCompose("./testresources/docker-compose-simple.yml")13 assert.NoError(t, err, "NewDockerCompose()")14 t.Cleanup(func() {15 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")16 })17 ctx, cancel := context.WithCancel(context.Background())18 t.Cleanup(cancel)19 assert.NoError(t, compose.Up(ctx, Wait(true)), "compose.Up()")20}21func TestDockerComposeAPIStrategyForInvalidService(t *testing.T) {22 compose, err := NewDockerCompose("./testresources/docker-compose-simple.yml")23 assert.NoError(t, err, "NewDockerCompose()")24 t.Cleanup(func() {25 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")26 })27 ctx, cancel := context.WithCancel(context.Background())28 t.Cleanup(cancel)29 err = compose.30 // Appending with _1 as given in the Java Test-Containers Example31 WaitForService("mysql-1", wait.NewLogStrategy("started").WithStartupTimeout(10*time.Second).WithOccurrence(1)).32 Up(ctx, Wait(true))33 assert.Error(t, err, "Expected error to be thrown because service with wait strategy is not running")34 assert.Equal(t, err.Error(), "no container found for service name mysql-1")35 serviceNames := compose.Services()36 assert.Equal(t, 1, len(serviceNames))37 assert.Contains(t, serviceNames, "nginx")38}39func TestDockerComposeAPIWithWaitLogStrategy(t *testing.T) {40 compose, err := NewDockerCompose("./testresources/docker-compose-complex.yml")41 assert.NoError(t, err, "NewDockerCompose()")42 t.Cleanup(func() {43 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")44 })45 ctx, cancel := context.WithCancel(context.Background())46 t.Cleanup(cancel)47 err = compose.48 WaitForService("mysql", wait.NewLogStrategy("started").WithStartupTimeout(10*time.Second).WithOccurrence(1)).49 Up(ctx, Wait(true))50 assert.NoError(t, err, "compose.Up()")51 serviceNames := compose.Services()52 assert.Equal(t, 2, len(serviceNames))53 assert.Contains(t, serviceNames, "nginx")54 assert.Contains(t, serviceNames, "mysql")55}56func TestDockerComposeAPIWithRunServices(t *testing.T) {57 compose, err := NewDockerCompose("./testresources/docker-compose-complex.yml")58 assert.NoError(t, err, "NewDockerCompose()")59 t.Cleanup(func() {60 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")61 })62 ctx, cancel := context.WithCancel(context.Background())63 t.Cleanup(cancel)64 err = compose.65 WaitForService("nginx", wait.NewHTTPStrategy("/").WithPort("80/tcp").WithStartupTimeout(10*time.Second)).66 Up(ctx, Wait(true), RunServices("nginx"))67 assert.NoError(t, err, "compose.Up()")68 serviceNames := compose.Services()69 _, err = compose.ServiceContainer(context.Background(), "mysql")70 assert.Error(t, err, "Make sure there is no mysql container")71 assert.Equal(t, 1, len(serviceNames))72 assert.Contains(t, serviceNames, "nginx")73}74func TestDockerComposeAPIWithWaitForService(t *testing.T) {75 compose, err := NewDockerCompose("./testresources/docker-compose-simple.yml")76 assert.NoError(t, err, "NewDockerCompose()")77 t.Cleanup(func() {78 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")79 })80 ctx, cancel := context.WithCancel(context.Background())81 t.Cleanup(cancel)82 err = compose.83 WithEnv(map[string]string{84 "bar": "BAR",85 }).86 WaitForService("nginx", wait.NewHTTPStrategy("/").WithPort("80/tcp").WithStartupTimeout(10*time.Second)).87 Up(ctx, Wait(true))88 assert.NoError(t, err, "compose.Up()")89 serviceNames := compose.Services()90 assert.Equal(t, 1, len(serviceNames))91 assert.Contains(t, serviceNames, "nginx")92}93func TestDockerComposeAPIWithWaitHTTPStrategy(t *testing.T) {94 compose, err := NewDockerCompose("./testresources/docker-compose-simple.yml")95 assert.NoError(t, err, "NewDockerCompose()")96 t.Cleanup(func() {97 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")98 })99 ctx, cancel := context.WithCancel(context.Background())100 t.Cleanup(cancel)101 err = compose.102 WithEnv(map[string]string{103 "bar": "BAR",104 }).105 WaitForService("nginx", wait.NewHTTPStrategy("/").WithPort("80/tcp").WithStartupTimeout(10*time.Second)).106 Up(ctx, Wait(true))107 assert.NoError(t, err, "compose.Up()")108 serviceNames := compose.Services()109 assert.Equal(t, 1, len(serviceNames))110 assert.Contains(t, serviceNames, "nginx")111}112func TestDockerComposeAPIWithContainerName(t *testing.T) {113 compose, err := NewDockerCompose("./testresources/docker-compose-container-name.yml")114 assert.NoError(t, err, "NewDockerCompose()")115 t.Cleanup(func() {116 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")117 })118 ctx, cancel := context.WithCancel(context.Background())119 t.Cleanup(cancel)120 err = compose.121 WithEnv(map[string]string{122 "bar": "BAR",123 }).124 WaitForService("nginx", wait.NewHTTPStrategy("/").WithPort("80/tcp").WithStartupTimeout(10*time.Second)).125 Up(ctx, Wait(true))126 assert.NoError(t, err, "compose.Up()")127 serviceNames := compose.Services()128 assert.Equal(t, 1, len(serviceNames))129 assert.Contains(t, serviceNames, "nginx")130}131func TestDockerComposeAPIWithWaitStrategy_NoExposedPorts(t *testing.T) {132 compose, err := NewDockerCompose("./testresources/docker-compose-no-exposed-ports.yml")133 assert.NoError(t, err, "NewDockerCompose()")134 t.Cleanup(func() {135 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")136 })137 ctx, cancel := context.WithCancel(context.Background())138 t.Cleanup(cancel)139 err = compose.140 WaitForService("nginx", wait.ForLog("Configuration complete; ready for start up")).141 Up(ctx, Wait(true))142 assert.NoError(t, err, "compose.Up()")143 serviceNames := compose.Services()144 assert.Equal(t, 1, len(serviceNames))145 assert.Contains(t, serviceNames, "nginx")146}147func TestDockerComposeAPIWithMultipleWaitStrategies(t *testing.T) {148 compose, err := NewDockerCompose("./testresources/docker-compose-complex.yml")149 assert.NoError(t, err, "NewDockerCompose()")150 t.Cleanup(func() {151 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")152 })153 ctx, cancel := context.WithCancel(context.Background())154 t.Cleanup(cancel)155 err = compose.156 WaitForService("mysql", wait.NewLogStrategy("started").WithStartupTimeout(10*time.Second)).157 WaitForService("nginx", wait.NewHTTPStrategy("/").WithPort("80/tcp").WithStartupTimeout(10*time.Second)).158 Up(ctx, Wait(true))159 assert.NoError(t, err, "compose.Up()")160 serviceNames := compose.Services()161 assert.Equal(t, 2, len(serviceNames))162 assert.Contains(t, serviceNames, "nginx")163 assert.Contains(t, serviceNames, "mysql")164}165func TestDockerComposeAPIWithFailedStrategy(t *testing.T) {166 compose, err := NewDockerCompose("./testresources/docker-compose-simple.yml")167 assert.NoError(t, err, "NewDockerCompose()")168 t.Cleanup(func() {169 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")170 })171 ctx, cancel := context.WithCancel(context.Background())172 t.Cleanup(cancel)173 err = compose.174 WithEnv(map[string]string{175 "bar": "BAR",176 }).177 WaitForService("nginx_1", wait.NewHTTPStrategy("/").WithPort("8080/tcp").WithStartupTimeout(5*time.Second)).178 Up(ctx, Wait(true))179 // Verify that an error is thrown and not nil180 // A specific error message matcher is not asserted since the docker library can change the return message, breaking this test181 assert.Error(t, err, "Expected error to be thrown because of a wrong suplied wait strategy")182 serviceNames := compose.Services()183 assert.Equal(t, 1, len(serviceNames))184 assert.Contains(t, serviceNames, "nginx")185}186func TestDockerComposeAPIComplex(t *testing.T) {187 compose, err := NewDockerCompose("./testresources/docker-compose-complex.yml")188 assert.NoError(t, err, "NewDockerCompose()")189 t.Cleanup(func() {190 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")191 })192 ctx, cancel := context.WithCancel(context.Background())193 t.Cleanup(cancel)194 assert.NoError(t, compose.Up(ctx, Wait(true)), "compose.Up()")195 serviceNames := compose.Services()196 assert.Equal(t, 2, len(serviceNames))197 assert.Contains(t, serviceNames, "nginx")198 assert.Contains(t, serviceNames, "mysql")199}200func TestDockerComposeAPIWithEnvironment(t *testing.T) {201 identifier := testNameHash(t.Name())202 compose, err := NewDockerComposeWith(WithStackFiles("./testresources/docker-compose-simple.yml"), identifier)203 assert.NoError(t, err, "NewDockerCompose()")204 t.Cleanup(func() {205 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")206 })207 ctx, cancel := context.WithCancel(context.Background())208 t.Cleanup(cancel)209 err = compose.210 WithEnv(map[string]string{211 "bar": "BAR",212 }).213 Up(ctx, Wait(true))214 assert.NoError(t, err, "compose.Up()")215 serviceNames := compose.Services()216 assert.Equal(t, 1, len(serviceNames))217 assert.Contains(t, serviceNames, "nginx")218 present := map[string]string{219 "bar": "BAR",220 }221 absent := map[string]string{}222 assertContainerEnvironmentVariables(t, identifier.String(), "nginx", present, absent)223}224func TestDockerComposeAPIWithMultipleComposeFiles(t *testing.T) {225 composeFiles := ComposeStackFiles{226 "testresources/docker-compose-simple.yml",227 "testresources/docker-compose-postgres.yml",228 "testresources/docker-compose-override.yml",229 }230 identifier := testNameHash(t.Name())231 compose, err := NewDockerComposeWith(composeFiles, identifier)232 assert.NoError(t, err, "NewDockerCompose()")233 t.Cleanup(func() {234 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")235 })236 ctx, cancel := context.WithCancel(context.Background())237 t.Cleanup(cancel)238 err = compose.239 WithEnv(map[string]string{240 "bar": "BAR",241 "foo": "FOO",242 }).243 Up(ctx, Wait(true))244 assert.NoError(t, err, "compose.Up()")245 serviceNames := compose.Services()246 assert.Equal(t, 3, len(serviceNames))247 assert.Contains(t, serviceNames, "nginx")248 assert.Contains(t, serviceNames, "mysql")249 assert.Contains(t, serviceNames, "postgres")250 present := map[string]string{251 "bar": "BAR",252 "foo": "FOO",253 }254 absent := map[string]string{}255 assertContainerEnvironmentVariables(t, identifier.String(), "nginx", present, absent)256}257func TestDockerComposeAPIWithVolume(t *testing.T) {258 compose, err := NewDockerCompose("./testresources/docker-compose-volume.yml")259 assert.NoError(t, err, "NewDockerCompose()")260 t.Cleanup(func() {261 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")262 })263 ctx, cancel := context.WithCancel(context.Background())264 t.Cleanup(cancel)265 err = compose.Up(ctx, Wait(true))266 assert.NoError(t, err, "compose.Up()")267}268func TestDockerComposeAPIWithBuild(t *testing.T) {269 compose, err := NewDockerCompose("./testresources/docker-compose-build.yml")270 assert.NoError(t, err, "NewDockerCompose()")271 t.Cleanup(func() {272 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")273 })274 ctx, cancel := context.WithCancel(context.Background())275 t.Cleanup(cancel)276 err = compose.277 WaitForService("echo", wait.ForHTTP("/env").WithPort("8080/tcp")).278 Up(ctx, Wait(true))279 assert.NoError(t, err, "compose.Up()")280}281func TestDockerComposeApiWithWaitForShortLifespanService(t *testing.T) {282 compose, err := NewDockerCompose("./testresources/docker-compose-short-lifespan.yml")283 assert.NoError(t, err, "NewDockerCompose()")284 t.Cleanup(func() {285 assert.NoError(t, compose.Down(context.Background(), RemoveOrphans(true), RemoveImagesLocal), "compose.Down()")286 })287 ctx, cancel := context.WithCancel(context.Background())288 t.Cleanup(cancel)289 err = compose.290 //Assumption: tzatziki service wait logic will run before falafel, so that falafel service will exit before291 WaitForService("tzatziki", wait.ForExit().WithExitTimeout(10*time.Second)).292 WaitForService("falafel", wait.ForExit().WithExitTimeout(10*time.Second)).293 Up(ctx)294 assert.NoError(t, err, "compose.Up()")295 services := compose.Services()296 assert.Equal(t, 2, len(services))297 assert.Contains(t, services, "falafel")...
compose.go
Source:compose.go
...77}78func WithStackFiles(filePaths ...string) ComposeStackOption {79 return ComposeStackFiles(filePaths)80}81func NewDockerCompose(filePaths ...string) (*dockerCompose, error) {82 return NewDockerComposeWith(WithStackFiles(filePaths...))83}84func NewDockerComposeWith(opts ...ComposeStackOption) (*dockerCompose, error) {85 composeOptions := composeStackOptions{86 Identifier: uuid.New().String(),87 }88 for i := range opts {89 opts[i].applyToComposeStack(&composeOptions)90 }91 if len(composeOptions.Paths) < 1 {92 return nil, ErrNoStackConfigured93 }94 dockerCli, err := command.NewDockerCli()95 if err != nil {96 return nil, err97 }98 if err = dockerCli.Initialize(&flags.ClientOptions{99 Common: new(flags.CommonOptions),100 }, command.WithInitializeClient(makeClient)); err != nil {101 return nil, err102 }103 composeAPI := &dockerCompose{104 name: composeOptions.Identifier,105 configs: composeOptions.Paths,106 composeService: compose.NewComposeService(dockerCli),107 dockerClient: dockerCli.Client(),108 waitStrategies: make(map[string]wait.Strategy),109 containers: make(map[string]*DockerContainer),110 }111 // log docker server info only once112 composeLogOnce.Do(func() {113 logDockerServerInfo(context.Background(), dockerCli.Client(), Logger)114 })115 return composeAPI, nil116}117// NewLocalDockerCompose returns an instance of the local Docker Compose, using an118// array of Docker Compose file paths and an identifier for the Compose execution.119//120// It will iterate through the array adding '-f compose-file-path' flags to the local121// Docker Compose execution. The identifier represents the name of the execution,122// which will define the name of the underlying Docker network and the name of the123// running Compose services.124//125// Deprecated: NewLocalDockerCompose returns a DockerCompose compatible instance which is superseded126// by ComposeStack use NewDockerCompose instead to get a ComposeStack compatible instance127func NewLocalDockerCompose(filePaths []string, identifier string, opts ...LocalDockerComposeOption) *LocalDockerCompose {128 dc := &LocalDockerCompose{129 LocalDockerComposeOptions: &LocalDockerComposeOptions{130 Logger: Logger,131 },132 }133 for idx := range opts {134 opts[idx].ApplyToLocalCompose(dc.LocalDockerComposeOptions)135 }136 dc.Executable = "docker-compose"137 if runtime.GOOS == "windows" {138 dc.Executable = "docker-compose.exe"139 }140 dc.ComposeFilePaths = filePaths...
NewDockerCompose
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"9200/tcp"},6 WaitingFor: wait.ForLog("started"),7 }8 elasticsearch, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer elasticsearch.Terminate(ctx)14 ip, err := elasticsearch.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := elasticsearch.MappedPort(ctx, "9200")19 if err != nil {20 panic(err)21 }22}
NewDockerCompose
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 dockerComposeFile, _ := filepath.Abs("./docker-compose.yml")5 dockerCompose := testcontainers.NewLocalDockerCompose(dockerComposeFile, "docker-compose")6 err := dockerCompose.WithCommand([]string{"up", "-d"}).Invoke(ctx)7 if err != nil {8 log.Fatal(err)9 }10 waitFor := wait.ForLog("postgres").WithOccurrence(1)11 err = dockerCompose.WithCommand([]string{"wait", "postgres"}).Invoke(ctx, waitFor)12 if err != nil {13 log.Fatal(err)14 }15 host, err := dockerCompose.GetServiceHostPort(ctx, "postgres", "5432/tcp")16 if err != nil {17 log.Fatal(err)18 }19 containerID, err := dockerCompose.GetServiceContainerID(ctx, "postgres")20 if err != nil {21 log.Fatal(err)22 }23 fmt.Printf("Host: %s
NewDockerCompose
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 postgres, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer postgres.Terminate(ctx)14 ip, err := postgres.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 mappedPort, err := postgres.MappedPort(ctx, "5432")19 if err != nil {20 log.Fatal(err)21 }22 fmt.Printf("Postgres is available at %s:%s", ip, mappedPort.Port())23}
NewDockerCompose
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"22/tcp"},6 WaitingFor: wait.ForLog("Starting Docker Compose..."),7 }8 dockerComposeContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 dockerComposeContainerID, err := dockerComposeContainer.ContainerID(ctx)14 if err != nil {15 panic(err)16 }17 fmt.Println("Container ID: ", dockerComposeContainerID)18 dockerComposeContainerIP, err := dockerComposeContainer.Host(ctx)19 if err != nil {20 panic(err)21 }22 fmt.Println("Container IP: ", dockerComposeContainerIP)23 dockerComposeContainerPort, err := dockerComposeContainer.MappedPort(ctx, "22")24 if err != nil {25 panic(err)26 }27 fmt.Println("Container Port: ", dockerComposeContainerPort.Int())28 dockerComposeContainerInfo, err := dockerComposeContainer.Inspect(ctx)29 if err != nil {30 panic(err)31 }32 fmt.Println("Container Info: ", dockerComposeContainerInfo
NewDockerCompose
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 Env: map[string]string{8 },9 }10 postgres, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{11 })12 if err != nil {13 panic(err)14 }15 defer postgres.Terminate(ctx)16 ip, err := postgres.Host(ctx)17 if err != nil {18 panic(err)19 }20 port, err := postgres.MappedPort(ctx, "5432/tcp")21 if err != nil {22 panic(err)23 }24 fmt.Printf("postgres is available on %s:%s", ip, port.Port())
NewDockerCompose
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 WaitingFor: wait.ForListeningPort("80/tcp"),7 }8 redis, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 ip, err := redis.Host(ctx)14 if err != nil {15 log.Fatal(err)16 }17 port, err := redis.MappedPort(ctx, "80")18 if err != nil {19 log.Fatal(err)20 }21 fmt.Printf("Container IP: %s, Port: %s22", ip, port.Port())23}
NewDockerCompose
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 compose, err := testcontainers.NewDockerCompose([]string{"docker-compose.yml"}, "compose")9 if err != nil {10 log.Fatal(err)11 }12 err = compose.WithCommand([]string{"up", "-d"}).Invoke(ctx)13 if err != nil {14 log.Fatal(err)15 }16 defer compose.Down(ctx)17 containerID, err := compose.ContainerID(ctx, "db")18 if err != nil {19 log.Fatal(err)20 }21 port, err := compose.Port(ctx, "db", "3306/tcp")22 if err != nil {23 log.Fatal(err)24 }25 fmt.Println(containerID)26 fmt.Println(port)27 time.Sleep(5 * time.Second)28}
NewDockerCompose
Using AI Code Generation
1import (2func main() {3 dockerCompose, err := testcontainers.NewDockerCompose([]string{"docker-compose.yml"}, "project")4 if err != nil {5 fmt.Println("Error creating docker compose", err)6 os.Exit(1)7 }8 err = dockerCompose.WithCommand([]string{"up", "-d"}).Invoke()9 if err != nil {10 fmt.Println("Error starting docker compose", err)11 os.Exit(1)12 }13 err = dockerCompose.WithCommand([]string{"down"}).Invoke()14 if err != nil {15 fmt.Println("Error stopping docker compose", err)16 os.Exit(1)17 }18}19dockerCompose.WithVersion("3.8")
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!!