Best Testcontainers-go code snippet using wait_test.Ports
http_test.go
Source:http_test.go
...20func ExampleHTTPStrategy() {21 ctx := context.Background()22 req := testcontainers.ContainerRequest{23 Image: "gogs/gogs:0.11.91",24 ExposedPorts: []string{"3000/tcp"},25 WaitingFor: wait.ForHTTP("/").WithPort("3000/tcp"),26 }27 gogs, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{28 ContainerRequest: req,29 Started: true,30 })31 if err != nil {32 panic(err)33 }34 defer gogs.Terminate(ctx) // nolint: errcheck35 // Here you have a running container36}37func TestHTTPStrategyWaitUntilReady(t *testing.T) {38 workdir, err := os.Getwd()39 if err != nil {40 t.Error(err)41 return42 }43 capath := workdir + "/testdata/root.pem"44 cafile, err := ioutil.ReadFile(capath)45 if err != nil {46 t.Errorf("can't load ca file: %v", err)47 return48 }49 certpool := x509.NewCertPool()50 if !certpool.AppendCertsFromPEM(cafile) {51 t.Errorf("the ca file isn't valid")52 return53 }54 tlsconfig := &tls.Config{RootCAs: certpool, ServerName: "testcontainer.go.test"}55 var i int56 dockerReq := testcontainers.ContainerRequest{57 FromDockerfile: testcontainers.FromDockerfile{58 Context: workdir + "/testdata",59 },60 ExposedPorts: []string{"6443/tcp"},61 WaitingFor: wait.NewHTTPStrategy("/ping").WithTLS(true, tlsconfig).62 WithStartupTimeout(time.Second * 10).WithPort("6443/tcp").63 WithResponseMatcher(func(body io.Reader) bool {64 data, _ := ioutil.ReadAll(body)65 return bytes.Equal(data, []byte("pong"))66 }).67 WithStatusCodeMatcher(func(status int) bool {68 i++ // always fail the first try in order to force the polling loop to be re-run69 return i > 1 && status == 20070 }).71 WithMethod(http.MethodPost).WithBody(bytes.NewReader([]byte("ping"))),72 }73 container, err := testcontainers.GenericContainer(context.Background(),74 testcontainers.GenericContainerRequest{ContainerRequest: dockerReq, Started: true})...
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!!