Skip to content

Commit

Permalink
chore: use require instead of t.Fatal (part 2)
Browse files Browse the repository at this point in the history
Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
  • Loading branch information
mmorel-35 committed Oct 30, 2024
1 parent a489482 commit d737429
Show file tree
Hide file tree
Showing 11 changed files with 70 additions and 165 deletions.
9 changes: 3 additions & 6 deletions lifecycle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -914,13 +914,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 err != nil && err.Error() == "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
Expand Down
15 changes: 6 additions & 9 deletions logconsumer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.Zerof(t, i, "Can't make request to nginx container from dind container")
require.NoError(t, err, "Can't make request to nginx container from dind container")
}

hitNginx()
Expand All @@ -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.Zerof(t, i, "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)
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.Zerof(t, i, "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)
time.Sleep(time.Second * 3)

hitNginx()
Expand Down
20 changes: 5 additions & 15 deletions modules/chroma/chroma_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
22 changes: 7 additions & 15 deletions modules/compose/compose_builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/require"
)

const (
Expand Down Expand Up @@ -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
Expand All @@ -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 {
Expand All @@ -158,19 +154,15 @@ 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)
}
require.NoErrorf(t, err, "creating output file")
defer 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
}
39 changes: 10 additions & 29 deletions modules/compose/compose_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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)
Expand Down
16 changes: 4 additions & 12 deletions modules/couchbase/couchbase_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"])
Expand Down
81 changes: 24 additions & 57 deletions modules/elasticsearch/elasticsearch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,65 +92,40 @@ 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)
// }
}

resp, err := httpClient.Do(req)
if resp != nil {
defer resp.Body.Close()
}
require.NotNil(t, resp)
defer resp.Body.Close()
require.NoError(t, err)

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)

if tt.image == baseImage7 {
require.Equalf(t, "7.9.2", esResp.Version.Number, "expected version to be 7.9.2 but got: %s", esResp.Version.Number)
} else if tt.image == 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)
})
}
}
Expand Down Expand Up @@ -185,9 +160,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")
})
}
}
Expand All @@ -208,19 +181,15 @@ 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()

var esResp ElasticsearchResponse
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) {
Expand All @@ -230,9 +199,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.
Expand Down
4 changes: 1 addition & 3 deletions modules/influxdb/influxdb_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Loading

0 comments on commit d737429

Please sign in to comment.