Best Testcontainers-go code snippet using testcontainers.TestDockerComposeAPI
compose_api_test.go
Source:compose_api_test.go
...7 "time"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")...
TestDockerComposeAPI
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 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 port, err := redis.MappedPort(ctx, "6379/tcp")19 if err != nil {20 panic(err)21 }22 fmt.Println(ip, port.Int())23}
TestDockerComposeAPI
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"9200/tcp"},6 WaitingFor: wait.ForListeningPort("9200/tcp"),7 }8 elasticsearchContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 ip, err := elasticsearchContainer.Host(ctx)14 if err != nil {15 panic(err)16 }17 port, err := elasticsearchContainer.MappedPort(ctx, "9200/tcp")18 if err != nil {19 panic(err)20 }21 fmt.Println(ip, port.Int())22}
TestDockerComposeAPI
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"9200/tcp", "9300/tcp"},6 WaitingFor: wait.ForLog("started"),7 }8 elasticsearchContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer elasticsearchContainer.Terminate(ctx)14 ip, err := elasticsearchContainer.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := elasticsearchContainer.MappedPort(ctx, "9200")19 if err != nil {20 panic(err)21 }22 fmt.Println("Elasticsearch is listening on ", ip, ":", port.Int())23}
TestDockerComposeAPI
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"8091-8094", "11210-11211"},6 WaitingFor: wait.ForLog("The default bucket has been created and is ready for use"),7 }8 couchbaseContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 log.Fatal(err)12 }13 defer couchbaseContainer.Terminate(ctx)14 ip, err := couchbaseContainer.Host(ctx)15 if err != nil {16 log.Fatal(err)17 }18 port, err := couchbaseContainer.MappedPort(ctx, "8091")19 if err != nil {20 log.Fatal(err)21 }22 id, err := couchbaseContainer.ContainerID(ctx)23 if err != nil {24 log.Fatal(err)25 }26 fmt.Printf("Container ID: %s27", ip, port.Port())28 time.Sleep(2 * time.Second)29}30import (31func main() {32 ctx := context.Background()33 req := testcontainers.ContainerRequest{34 ExposedPorts: []string{"8091-8094", "11210-11211"},35 WaitingFor: wait.ForLog("The default bucket has been created and is ready for use"),36 }37 couchbaseContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{38 })39 if err != nil {
TestDockerComposeAPI
Using AI Code Generation
1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"5432/tcp"},6 WaitingFor: wait.ForLog("database system is ready to accept connections"),7 }8 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer postgresContainer.Terminate(ctx)14 ip, err := postgresContainer.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := postgresContainer.MappedPort(ctx, "5432")19 if err != nil {20 panic(err)21 }22 fmt.Printf("postgresql port is %s23", port.Port())24 fmt.Printf("postgresql ip is %s25}26import (27func main() {28 ctx := context.Background()29 req := testcontainers.ContainerRequest{30 ExposedPorts: []string{"5432/tcp"},31 WaitingFor: wait.ForLog("database system is ready to accept connections"),32 }33 postgresContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{34 })35 if err != nil {36 panic(err)37 }38 defer postgresContainer.Terminate(ctx)39 ip, err := postgresContainer.Host(ctx)40 if err != nil {41 panic(err)42 }43 port, err := postgresContainer.MappedPort(ctx, "5432")44 if err != nil {45 panic(err)46 }47 fmt.Printf("postgresql port is %s48", port.Port())49 fmt.Printf("postgresql ip is %s50}
TestDockerComposeAPI
Using AI Code Generation
1import (2func TestDockerComposeAPI() {3 ctx := context.Background()4 compose := testcontainers.NewLocalDockerCompose([]string{"docker-compose.yml"}, "test")5 Invoke(ctx)6 if err != nil {7 panic(err)8 }9 Invoke(ctx)10 if err != nil {11 panic(err)12 }13 Invoke(ctx)14 if err != nil {15 panic(err)16 }17}18func main() {19 TestDockerComposeAPI()20}
TestDockerComposeAPI
Using AI Code Generation
1import (2func TestDockerComposeAPI(t *testing.T) {3 ctx := context.Background()4 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())5 if err != nil {6 panic(err)7 }8 pwd, err := os.Getwd()9 if err != nil {10 panic(err)11 }12 cmd := exec.Command("docker-compose", "-f", composePath, "up", "-d")13 if err := cmd.Run(); err != nil {14 t.Fatalf("Could not run docker-compose: %v", err)15 }16 fmt.Println("docker-compose stack started")17 defer func() {18 cmd = exec.Command("docker-compose", "-f", composePath, "down")19 if err := cmd.Run(); err != nil {20 t.Fatalf("Could not run docker-compose: %v", err)21 }22 fmt.Println("docker-compose stack stopped")23 }()24 time.Sleep(10 * time.Second)25 containers, err := cli.ContainerList(ctx, types.ContainerListOptions{})26 if err != nil {27 panic(err)28 }29 for _, container := range containers {30 fmt.Println(container.ID)31 }32}33import (34func TestDockerComposeAPI(t *testing.T) {35 ctx := context.Background()36 cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())37 if err != nil {38 panic(err)39 }40 pwd, err := os.Getwd()41 if err != nil {42 panic(err)43 }
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!!