Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: use require instead of t.Fatal (part 2) #2857

Merged
merged 1 commit into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions lifecycle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package testcontainers
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -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
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.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()
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.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()
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)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an example of a message that people might think is helpful but isn't in my mind as the values are output anyway and is obvious from the code its a status check.

})

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
26 changes: 10 additions & 16 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,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
}
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
Loading