diff --git a/lifecycle_test.go b/lifecycle_test.go index c683a4146c..0faefa8769 100644 --- a/lifecycle_test.go +++ b/lifecycle_test.go @@ -3,7 +3,9 @@ package testcontainers import ( "bufio" "context" + "errors" "fmt" + "io" "strings" "testing" "time" @@ -914,13 +916,10 @@ func TestPrintContainerLogsOnError(t *testing.T) { rd := bufio.NewReader(containerLogs) for { line, err := rd.ReadString('\n') - if err != nil { - if err.Error() == "EOF" { - break - } - - t.Fatal("Read Error:", err) + if errors.Is(err, io.EOF) { + break } + require.NoErrorf(t, err, "Read Error") // the last line of the array should contain the line of interest, // but we are checking all the lines to make sure that is present diff --git a/logconsumer_test.go b/logconsumer_test.go index 35fc98ae8a..dae1ea0b5a 100644 --- a/logconsumer_test.go +++ b/logconsumer_test.go @@ -323,9 +323,8 @@ func TestContainerLogWithErrClosed(t *testing.T) { hitNginx := func() { i, _, err := dind.Exec(ctx, []string{"wget", "--spider", "localhost:" + port.Port()}) - if err != nil || i > 0 { - t.Fatalf("Can't make request to nginx container from dind container") - } + require.NoError(t, err, "Can't make request to nginx container from dind container") + require.Zerof(t, i, "Can't make request to nginx container from dind container") } hitNginx() @@ -340,13 +339,11 @@ func TestContainerLogWithErrClosed(t *testing.T) { } // Simulate a transient closed connection to the docker daemon i, _, err := dind.Exec(ctx, append([]string{"iptables", "-A"}, iptableArgs...)) - if err != nil || i > 0 { - t.Fatalf("Failed to close connection to dind daemon: i(%d), err %v", i, err) - } + require.NoErrorf(t, err, "Failed to close connection to dind daemon: i(%d), err %v", i, err) + require.Zerof(t, i, "Failed to close connection to dind daemon: i(%d), err %v", i, err) i, _, err = dind.Exec(ctx, append([]string{"iptables", "-D"}, iptableArgs...)) - if err != nil || i > 0 { - t.Fatalf("Failed to re-open connection to dind daemon: i(%d), err %v", i, err) - } + require.NoErrorf(t, err, "Failed to re-open connection to dind daemon: i(%d), err %v", i, err) + require.Zerof(t, i, "Failed to re-open connection to dind daemon: i(%d), err %v", i, err) time.Sleep(time.Second * 3) hitNginx() diff --git a/modules/chroma/chroma_test.go b/modules/chroma/chroma_test.go index 5bf44b3282..5d975c3602 100644 --- a/modules/chroma/chroma_test.go +++ b/modules/chroma/chroma_test.go @@ -23,33 +23,23 @@ func TestChroma(t *testing.T) { // restEndpoint { restEndpoint, err := ctr.RESTEndpoint(ctx) // } - if err != nil { - tt.Fatalf("failed to get REST endpoint: %s", err) - } + require.NoErrorf(tt, err, "failed to get REST endpoint") cli := &http.Client{} resp, err := cli.Get(restEndpoint + "/docs") - if err != nil { - tt.Fatalf("failed to perform GET request: %s", err) - } + require.NoErrorf(tt, err, "failed to perform GET request") defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - tt.Fatalf("unexpected status code: %d", resp.StatusCode) - } + require.Equalf(tt, http.StatusOK, resp.StatusCode, "unexpected status code: %d", resp.StatusCode) }) t.Run("GetClient", func(tt *testing.T) { // restEndpoint { endpoint, err := ctr.RESTEndpoint(context.Background()) - if err != nil { - tt.Fatalf("failed to get REST endpoint: %s", err) - } + require.NoErrorf(tt, err, "failed to get REST endpoint") chromaClient, err := chromago.NewClient(endpoint) // } - if err != nil { - tt.Fatalf("failed to create client: %s", err) - } + require.NoErrorf(tt, err, "failed to create client") hb, err := chromaClient.Heartbeat(context.TODO()) require.NoError(tt, err) diff --git a/modules/compose/compose_builder_test.go b/modules/compose/compose_builder_test.go index 07b3c08aba..048bac241b 100644 --- a/modules/compose/compose_builder_test.go +++ b/modules/compose/compose_builder_test.go @@ -8,6 +8,8 @@ import ( "os" "path/filepath" "testing" + + "github.com/stretchr/testify/require" ) const ( @@ -121,14 +123,10 @@ func getFreePort(t *testing.T) int { t.Helper() addr, err := net.ResolveTCPAddr("tcp", "localhost:0") - if err != nil { - t.Fatalf("failed to resolve TCP address: %v", err) - } + require.NoErrorf(t, err, "failed to resolve TCP address") l, err := net.ListenTCP("tcp", addr) - if err != nil { - t.Fatalf("failed to listen on TCP address: %v", err) - } + require.NoErrorf(t, err, "failed to listen on TCP address") defer l.Close() return l.Addr().(*net.TCPAddr).Port @@ -146,9 +144,7 @@ func writeTemplateWithSrvType(t *testing.T, templateFile string, srvType string, composeFile := filepath.Join(tmpDir, "docker-compose.yml") tmpl, err := template.ParseFiles(filepath.Join(testdataPackage, templateFile)) - if err != nil { - t.Fatalf("parsing template file: %s", err) - } + require.NoErrorf(t, err, "parsing template file") values := map[string]interface{}{} for i, p := range port { @@ -158,19 +154,17 @@ func writeTemplateWithSrvType(t *testing.T, templateFile string, srvType string, values["ServiceType"] = srvType output, err := os.Create(composeFile) - if err != nil { - t.Fatalf("creating output file: %s", err) - } - defer output.Close() + require.NoErrorf(t, err, "creating output file") + defer func() { + require.NoError(t, output.Close()) + }() executeTemplateFile := func(templateFile *template.Template, wr io.Writer, data any) error { return templateFile.Execute(wr, data) } err = executeTemplateFile(tmpl, output, values) - if err != nil { - t.Fatalf("executing template file: %s", err) - } + require.NoErrorf(t, err, "executing template file") return composeFile } diff --git a/modules/compose/compose_test.go b/modules/compose/compose_test.go index 39f502fcf3..24c0c6c635 100644 --- a/modules/compose/compose_test.go +++ b/modules/compose/compose_test.go @@ -448,22 +448,16 @@ func TestLocalDockerComposeWithVolume(t *testing.T) { func assertVolumeDoesNotExist(tb testing.TB, volumeName string) { tb.Helper() containerClient, err := testcontainers.NewDockerClientWithOpts(context.Background()) - if err != nil { - tb.Fatalf("Failed to get provider: %v", err) - } + require.NoErrorf(tb, err, "Failed to get provider") volumeList, err := containerClient.VolumeList(context.Background(), volume.ListOptions{Filters: filters.NewArgs(filters.Arg("name", volumeName))}) - if err != nil { - tb.Fatalf("Failed to list volumes: %v", err) - } + require.NoErrorf(tb, err, "Failed to list volumes") if len(volumeList.Warnings) > 0 { tb.Logf("Volume list warnings: %v", volumeList.Warnings) } - if len(volumeList.Volumes) > 0 { - tb.Fatalf("Volume list is not empty") - } + require.Emptyf(tb, volumeList.Volumes, "Volume list is not empty") } func assertContainerEnvironmentVariables( @@ -474,16 +468,11 @@ func assertContainerEnvironmentVariables( ) { tb.Helper() containerClient, err := testcontainers.NewDockerClientWithOpts(context.Background()) - if err != nil { - tb.Fatalf("Failed to get provider: %v", err) - } + require.NoErrorf(tb, err, "Failed to get provider") containers, err := containerClient.ContainerList(context.Background(), container.ListOptions{}) - if err != nil { - tb.Fatalf("Failed to list containers: %v", err) - } else if len(containers) == 0 { - tb.Fatalf("container list empty") - } + require.NoErrorf(tb, err, "Failed to list containers") + require.NotEmptyf(tb, containers, "container list empty") containerNameRegexp := regexp.MustCompile(fmt.Sprintf(`^\/?%s(_|-)%s(_|-)\d$`, composeIdentifier, serviceName)) var containerID string @@ -499,9 +488,7 @@ containerLoop: } details, err := containerClient.ContainerInspect(context.Background(), containerID) - if err != nil { - tb.Fatalf("Failed to inspect container: %v", err) - } + require.NoErrorf(tb, err, "Failed to inspect container") for k, v := range present { keyVal := k + "=" + v @@ -516,17 +503,11 @@ containerLoop: func checkIfError(t *testing.T, err ExecError) { t.Helper() - if err.Error != nil { - t.Fatalf("Failed when running %v: %v", err.Command, err.Error) - } + require.NoErrorf(t, err.Error, "Failed when running %v", err.Command) - if err.Stdout != nil { - t.Fatalf("An error in Stdout happened when running %v: %v", err.Command, err.Stdout) - } + require.NoErrorf(t, err.Stdout, "An error in Stdout happened when running %v", err.Command) - if err.Stderr != nil { - t.Fatalf("An error in Stderr happened when running %v: %v", err.Command, err.Stderr) - } + require.NoErrorf(t, err.Stderr, "An error in Stderr happened when running %v", err.Command) assert.NotNil(t, err.StdoutOutput) assert.NotNil(t, err.StderrOutput) diff --git a/modules/couchbase/couchbase_test.go b/modules/couchbase/couchbase_test.go index 4e6330e24d..2e2122e01b 100644 --- a/modules/couchbase/couchbase_test.go +++ b/modules/couchbase/couchbase_test.go @@ -115,29 +115,21 @@ func TestEventingServiceWithCommunityContainer(t *testing.T) { func testBucketUsage(t *testing.T, bucket *gocb.Bucket) { t.Helper() err := bucket.WaitUntilReady(5*time.Second, nil) - if err != nil { - t.Fatalf("could not connect bucket: %s", err) - } + require.NoErrorf(t, err, "could not connect bucket") key := "foo" data := map[string]string{"key": "value"} collection := bucket.DefaultCollection() _, err = collection.Upsert(key, data, nil) - if err != nil { - t.Fatalf("could not upsert data: %s", err) - } + require.NoErrorf(t, err, "could not upsert data") result, err := collection.Get(key, nil) - if err != nil { - t.Fatalf("could not get data: %s", err) - } + require.NoErrorf(t, err, "could not get data") var resultData map[string]string err = result.Content(&resultData) - if err != nil { - t.Fatalf("could not assign content: %s", err) - } + require.NoErrorf(t, err, "could not assign content") if resultData["key"] != "value" { t.Errorf("Expected value to be [%s], got %s", "value", resultData["key"]) diff --git a/modules/elasticsearch/elasticsearch_test.go b/modules/elasticsearch/elasticsearch_test.go index 99829e94d3..14c5640e72 100644 --- a/modules/elasticsearch/elasticsearch_test.go +++ b/modules/elasticsearch/elasticsearch_test.go @@ -92,9 +92,7 @@ func TestElasticsearch(t *testing.T) { // set the password for the request using the Authentication header if tt.passwordCustomiser != nil { - if esContainer.Settings.Username != "elastic" { - t.Fatal("expected username to be elastic but got", esContainer.Settings.Username) - } + require.Equalf(t, "elastic", esContainer.Settings.Username, "expected username to be elastic but got: %s", esContainer.Settings.Username) // basicAuthHeader { req.SetBasicAuth(esContainer.Settings.Username, esContainer.Settings.Password) @@ -102,55 +100,33 @@ func TestElasticsearch(t *testing.T) { } resp, err := httpClient.Do(req) - if resp != nil { - defer resp.Body.Close() - } + require.NoError(t, err) + require.NotNil(t, resp) + defer resp.Body.Close() + + if tt.image == baseImage8 && tt.passwordCustomiser == nil { + // Elasticsearch 8 should return 401 Unauthorized, not an error in the request + require.Equalf(t, http.StatusUnauthorized, resp.StatusCode, "expected 401 status code for unauthorised HTTP client using TLS, but got: %s", resp.StatusCode) - if tt.image != baseImage8 && err != nil { - if tt.passwordCustomiser != nil { - t.Fatal(err, "should access with authorised HTTP client.") - } else if tt.passwordCustomiser == nil { - t.Fatal(err, "should access with unauthorised HTTP client.") - } + // finish validating the response when the request is unauthorised + return } - if tt.image == baseImage8 { - if tt.passwordCustomiser != nil && err != nil { - t.Fatal(err, "should access with authorised HTTP client using TLS.") - } - if tt.passwordCustomiser == nil && err == nil { - // Elasticsearch 8 should return 401 Unauthorized, not an error in the request - if resp.StatusCode != http.StatusUnauthorized { - t.Fatal("expected 401 status code for unauthorised HTTP client using TLS, but got", resp.StatusCode) - } + // validate Elasticsearch response + require.Equalf(t, http.StatusOK, resp.StatusCode, "expected 200 status code but got: %s", resp.StatusCode) - // finish validating the response when the request is unauthorised - return - } + var esResp ElasticsearchResponse + err = json.NewDecoder(resp.Body).Decode(&esResp) + require.NoError(t, err) + switch tt.image { + case baseImage7: + require.Equalf(t, "7.9.2", esResp.Version.Number, "expected version to be 7.9.2 but got: %s", esResp.Version.Number) + case baseImage8: + require.Equalf(t, "8.9.0", esResp.Version.Number, "expected version to be 8.9.0 but got: %s", esResp.Version.Number) } - // validate response - if resp != nil { - // validate Elasticsearch response - if resp.StatusCode != http.StatusOK { - t.Fatal("expected 200 status code but got", resp.StatusCode) - } - - var esResp ElasticsearchResponse - err = json.NewDecoder(resp.Body).Decode(&esResp) - require.NoError(t, err) - - if tt.image == baseImage7 && esResp.Version.Number != "7.9.2" { - t.Fatal("expected version to be 7.9.2 but got", esResp.Version.Number) - } else if tt.image == baseImage8 && esResp.Version.Number != "8.9.0" { - t.Fatal("expected version to be 8.9.0 but got", esResp.Version.Number) - } - - if esResp.Tagline != "You Know, for Search" { - t.Fatal("expected tagline to be 'You Know, for Search' but got", esResp.Tagline) - } - } + require.Equalf(t, "You Know, for Search", esResp.Tagline, "expected tagline to be 'You Know, for Search' but got: %s", esResp.Tagline) }) } } @@ -185,9 +161,7 @@ func TestElasticsearch8WithoutSSL(t *testing.T) { testcontainers.CleanupContainer(t, ctr) require.NoError(t, err) - if len(ctr.Settings.CACert) > 0 { - t.Fatal("expected CA cert to be empty") - } + require.Emptyf(t, ctr.Settings.CACert, "expected CA cert to be empty") }) } } @@ -208,9 +182,7 @@ func TestElasticsearch8WithoutCredentials(t *testing.T) { req.SetBasicAuth(ctr.Settings.Username, ctr.Settings.Password) resp, err := httpClient.Do(req) - if err != nil { - t.Fatal(err, "Should be able to access / URI with client using default password over HTTPS.") - } + require.NoErrorf(t, err, "Should be able to access / URI with client using default password over HTTPS.") defer resp.Body.Close() @@ -218,9 +190,7 @@ func TestElasticsearch8WithoutCredentials(t *testing.T) { err = json.NewDecoder(resp.Body).Decode(&esResp) require.NoError(t, err) - if esResp.Tagline != "You Know, for Search" { - t.Fatal("expected tagline to be 'You Know, for Search' but got", esResp.Tagline) - } + require.Equalf(t, "You Know, for Search", esResp.Tagline, "expected tagline to be 'You Know, for Search' but got: %s", esResp.Tagline) } func TestElasticsearchOSSCannotuseWithPassword(t *testing.T) { @@ -230,9 +200,7 @@ func TestElasticsearchOSSCannotuseWithPassword(t *testing.T) { ctr, err := elasticsearch.Run(ctx, ossImage, elasticsearch.WithPassword("foo")) testcontainers.CleanupContainer(t, ctr) - if err == nil { - t.Fatal(err, "Should not be able to use WithPassword with OSS image.") - } + require.Errorf(t, err, "Should not be able to use WithPassword with OSS image.") } // configureHTTPClient configures an HTTP client for the Elasticsearch container. diff --git a/modules/influxdb/influxdb_test.go b/modules/influxdb/influxdb_test.go index 08d9a72126..3c4379c66c 100644 --- a/modules/influxdb/influxdb_test.go +++ b/modules/influxdb/influxdb_test.go @@ -24,9 +24,7 @@ func TestV1Container(t *testing.T) { state, err := influxDbContainer.State(ctx) require.NoError(t, err) - if !state.Running { - t.Fatal("InfluxDB container is not running") - } + require.Truef(t, state.Running, "InfluxDB container is not running") } func TestV2Container(t *testing.T) { diff --git a/modules/neo4j/neo4j_test.go b/modules/neo4j/neo4j_test.go index 5918b7dc31..84272c93e9 100644 --- a/modules/neo4j/neo4j_test.go +++ b/modules/neo4j/neo4j_test.go @@ -39,9 +39,9 @@ func TestNeo4j(outer *testing.T) { "RETURN apoc.number.arabicToRoman(1986) AS output", nil, neo.EagerResultTransformer) require.NoErrorf(t, err, "expected APOC query to successfully run but did not") - if value, _ := result.Records[0].Get("output"); value != "MCMLXXXVI" { - t.Fatalf("did not get expected roman number: %s", value) - } + require.NotEmpty(t, result.Records) + value, _ := result.Records[0].Get("output") + require.Equalf(t, "MCMLXXXVI", value, "did not get expected roman number: %s", value) }) outer.Run("is configured with custom Neo4j settings", func(t *testing.T) { @@ -118,10 +118,8 @@ func TestNeo4jWithWrongSettings(outer *testing.T) { require.NoError(t, err) errorLogs := logger.Logs() - if !Contains(errorLogs, `setting "some.key" with value "value1" is now overwritten with value "value2"`+"\n") || - !Contains(errorLogs, `setting "some.key" with value "value2" is now overwritten with value "value3"`+"\n") { - t.Fatalf("expected setting overwrites to be logged") - } + require.Containsf(t, errorLogs, `setting "some.key" with value "value1" is now overwritten with value "value2"`+"\n", "expected setting overwrites to be logged") + require.Containsf(t, errorLogs, `setting "some.key" with value "value2" is now overwritten with value "value3"`+"\n", "expected setting overwrites to be logged") require.Containsf(t, getContainerEnv(t, ctx, ctr), "NEO4J_some_key=value3", "expected custom setting to be set with last value") }) @@ -129,9 +127,7 @@ func TestNeo4jWithWrongSettings(outer *testing.T) { ctr, err := neo4j.Run(ctx, "neo4j:4.4", neo4j.WithLogger(nil)) testcontainers.CleanupContainer(t, ctr) require.Nilf(t, ctr, "container must not be created with nil logger") - if err == nil || err.Error() != "nil logger is not permitted" { - t.Fatalf("expected config validation error but got no error") - } + require.EqualErrorf(t, err, "nil logger is not permitted", "expected config validation error but got no error") }) } diff --git a/modules/rabbitmq/rabbitmq_test.go b/modules/rabbitmq/rabbitmq_test.go index 1e05b8f3aa..1cdd7e9137 100644 --- a/modules/rabbitmq/rabbitmq_test.go +++ b/modules/rabbitmq/rabbitmq_test.go @@ -72,9 +72,7 @@ func TestRunContainer_connectUsingAmqps(t *testing.T) { amqpsURL, err := rabbitmqContainer.AmqpsURL(ctx) require.NoError(t, err) - if !strings.HasPrefix(amqpsURL, "amqps") { - t.Fatal(fmt.Errorf("AMQPS Url should begin with `amqps`")) - } + require.Truef(t, strings.HasPrefix(amqpsURL, "amqps"), "AMQPS Url should begin with `amqps`") certs := x509.NewCertPool() @@ -85,9 +83,7 @@ func TestRunContainer_connectUsingAmqps(t *testing.T) { amqpsConnection, err := amqp.DialTLS(amqpsURL, &tls.Config{InsecureSkipVerify: false, RootCAs: certs}) require.NoError(t, err) - if amqpsConnection.IsClosed() { - t.Fatal(fmt.Errorf("AMQPS Connection unexpectdely closed")) - } + require.Falsef(t, amqpsConnection.IsClosed(), "AMQPS Connection unexpectdely closed") err = amqpsConnection.Close() require.NoError(t, err) } diff --git a/modules/weaviate/weaviate_test.go b/modules/weaviate/weaviate_test.go index f1d6de3eeb..c85a25726c 100644 --- a/modules/weaviate/weaviate_test.go +++ b/modules/weaviate/weaviate_test.go @@ -66,8 +66,7 @@ func TestWeaviate(t *testing.T) { meta, err := client.Misc().MetaGetter().Do(ctx) require.NoError(tt, err) - if meta == nil || meta.Version == "" { - tt.Fatal("failed to get /v1/meta response") - } + require.NotNilf(tt, meta, "failed to get /v1/meta response") + require.NotEmptyf(tt, meta.Version, "failed to get /v1/meta response") }) }