Best Testcontainers-go code snippet using wait.WithStartupTimeout
magefile_sakila.go
Source: magefile_sakila.go
...26 {27 Image: "sakiladb/sqlserver:2017-CU19",28 Name: "sakiladb-sqlserver-2017",29 ExposedPorts: []string{"14337:1433"},30 WaitingFor: wait.ForLog("Changed database context to 'sakila'.").WithStartupTimeout(startupTimeout),31 },32 {33 Image: "sakiladb/postgres:9",34 Name: "sakiladb-postgres-9",35 ExposedPorts: []string{"54329:5432"},36 WaitingFor: wait.ForLog("PostgreSQL init process complete; ready for start up.").WithStartupTimeout(startupTimeout),37 },38 {39 Image: "sakiladb/postgres:10",40 Name: "sakiladb-postgres-10",41 ExposedPorts: []string{"54330:5432"},42 WaitingFor: wait.ForLog("PostgreSQL init process complete; ready for start up.").WithStartupTimeout(startupTimeout),43 },44 {45 Image: "sakiladb/postgres:11",46 Name: "sakiladb-postgres-11",47 ExposedPorts: []string{"54331:5432"},48 WaitingFor: wait.ForLog("PostgreSQL init process complete; ready for start up.").WithStartupTimeout(startupTimeout),49 },50 {51 Image: "sakiladb/postgres:12",52 Name: "sakiladb-postgres-12",53 ExposedPorts: []string{"54332:5432"},54 WaitingFor: wait.ForLog("PostgreSQL init process complete; ready for start up.").WithStartupTimeout(startupTimeout),55 },56 {57 Image: "sakiladb/mysql:5.6",58 Name: "sakiladb-mysql-5.6",59 ExposedPorts: []string{"33066:3306"},60 WaitingFor: wait.ForLog("[Note] mysqld: ready for connections.").WithStartupTimeout(startupTimeout),61 },62 {63 Image: "sakiladb/mysql:5.7",64 Name: "sakiladb-mysql-5.7",65 ExposedPorts: []string{"33067:3306"},66 WaitingFor: wait.ForLog("[Note] mysqld: ready for connections.").WithStartupTimeout(startupTimeout),67 },68 {69 Image: "sakiladb/mysql:8",70 Name: "sakiladb-mysql-8",71 ExposedPorts: []string{"33068:3306"},72 WaitingFor: wait.ForLog("[Server] /usr/sbin/mysqld: ready for connections.").WithStartupTimeout(startupTimeout),73 },74}75// StartAll starts all the sakila database server containers locally.76// Use RemoveAll to stop & remove the containers.77func (Sakila) StartAll() error {78 const envarInfo = `export SQ_TEST_SRC__SAKILA_MY56=localhost:3306679export SQ_TEST_SRC__SAKILA_MY57=localhost:3306780export SQ_TEST_SRC__SAKILA_MY8=localhost:3306881export SQ_TEST_SRC__SAKILA_PG9=localhost:5432982export SQ_TEST_SRC__SAKILA_PG10=localhost:5433083export SQ_TEST_SRC__SAKILA_PG11=localhost:5433184export SQ_TEST_SRC__SAKILA_PG12=localhost:5433285export SQ_TEST_SRC__SAKILA_MS17=localhost:14337`86 fmt.Println("Starting all containers...")...
testcontainer.go
Source: testcontainer.go
...32}33// fluent builders for each property34// since go has neither covariance nor generics, the return type must be the type of the concrete implementation35// this is true for all properties, even the "shared" ones like startupTimeout36// WithStartupTimeout can be used to change the default startup timeout37func (ws *DbStrategy) WithStartupTimeout(startupTimeout time.Duration) *DbStrategy {38 ws.startupTimeout = startupTimeout39 return ws40}41// WithPollInterval can be used to override the default polling interval of 100 milliseconds42func (ws *DbStrategy) WithPollInterval(pollInterval time.Duration) *DbStrategy {43 ws.PollInterval = pollInterval44 return ws45}46// WaitUntilReady implements Strategy.WaitUntilReady47func (ws *DbStrategy) WaitUntilReady(ctx context.Context, target wait.StrategyTarget) (err error) {48 // limit context to startupTimeout49 ctx, cancelContext := context.WithTimeout(ctx, ws.startupTimeout)50 defer cancelContext()51 if !strings.Contains(ws.dataSourceName, "<port>") {52 return faults.Errorf("missing placeholder <port> in %s", ws.dataSourceName)53 }54 var ds string55 for {56 select {57 case <-ctx.Done():58 return ctx.Err()59 default:60 var err error61 if ds == "" {62 var port nat.Port63 port, err = target.MappedPort(ctx, ws.port)64 if err == nil {65 ds = strings.ReplaceAll(ws.dataSourceName, "<port>", port.Port())66 }67 }68 if err == nil {69 _, err = Connect(ws.driverName, ds)70 }71 if err != nil {72 time.Sleep(ws.PollInterval)73 continue74 }75 return nil76 }77 }78}79func Container(80 image string,81 exPort string,82 env map[string]string,83 driverName string,84 dataSourceName string,85 timeout int,86) (context.Context, testcontainers.Container, nat.Port, error) {87 ctx := context.Background()88 req := testcontainers.ContainerRequest{89 Image: image,90 ExposedPorts: []string{exPort},91 Env: env,92 WaitingFor: ForDb(93 driverName,94 dataSourceName,95 exPort,96 ).WithStartupTimeout(time.Duration(timeout) * time.Minute),97 }98 server, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{99 ContainerRequest: req,100 Started: true,101 })102 var port nat.Port103 if err == nil {104 port, err = server.MappedPort(ctx, nat.Port(exPort))105 }106 return ctx, server, port, faults.Wrap(err)107}...
log_test.go
Source: log_test.go
...30func TestWaitForLog(t *testing.T) {31 target := noopStrategyTarget{32 ioReaderCloser: ioutil.NopCloser(bytes.NewReader([]byte("docker"))),33 }34 wg := NewLogStrategy("docker").WithStartupTimeout(100 * time.Microsecond)35 err := wg.WaitUntilReady(context.Background(), target)36 if err != nil {37 t.Fatal(err)38 }39}40func TestWaitWithExactNumberOfOccurrences(t *testing.T) {41 target := noopStrategyTarget{42 ioReaderCloser: ioutil.NopCloser(bytes.NewReader([]byte("kubernetes\r\ndocker\n\rdocker"))),43 }44 wg := NewLogStrategy("docker").45 WithStartupTimeout(100 * time.Microsecond).46 WithOccurrence(2)47 err := wg.WaitUntilReady(context.Background(), target)48 if err != nil {49 t.Fatal(err)50 }51}52func TestWaitWithExactNumberOfOccurrencesButItWillNeverHappen(t *testing.T) {53 target := noopStrategyTarget{54 ioReaderCloser: ioutil.NopCloser(bytes.NewReader([]byte("kubernetes\r\ndocker"))),55 }56 wg := NewLogStrategy("containerd").57 WithStartupTimeout(100 * time.Microsecond).58 WithOccurrence(2)59 err := wg.WaitUntilReady(context.Background(), target)60 if err == nil {61 t.Fatal("expected error")62 }63}64func TestWaitShouldFailWithExactNumberOfOccurrences(t *testing.T) {65 target := noopStrategyTarget{66 ioReaderCloser: ioutil.NopCloser(bytes.NewReader([]byte("kubernetes\r\ndocker"))),67 }68 wg := NewLogStrategy("docker").69 WithStartupTimeout(100 * time.Microsecond).70 WithOccurrence(2)71 err := wg.WaitUntilReady(context.Background(), target)72 if err == nil {73 t.Fatal("expected error")74 }75}...
Check out the latest blogs from LambdaTest on this topic:
One of the most important tasks of a software developer is not just writing code fast; it is the ability to find what causes errors and bugs whenever you encounter one and the ability to solve them quickly.
There is just one area where each member of the software testing community has a distinct point of view! Metrics! This contentious issue sparks intense disputes, and most conversations finish with no definitive conclusion. It covers a wide range of topics: How can testing efforts be measured? What is the most effective technique to assess effectiveness? Which of the many components should be quantified? How can we measure the quality of our testing performance, among other things?
We launched LT Browser in 2020, and we were overwhelmed by the response as it was awarded as the #5 product of the day on the ProductHunt platform. Today, after 74,585 downloads and 7,000 total test runs with an average of 100 test runs each day, the LT Browser has continued to help developers build responsive web designs in a jiffy.
With the rise of Agile, teams have been trying to minimize the gap between the stakeholders and the development team.
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!!