From b7511cd05427318872e29e3b7b8e6ad4d2ec6889 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Mon, 28 Oct 2024 10:25:18 +0100 Subject: [PATCH] chore: use require.(No)Error(t,err) instead of t.Fatal(err) (#2851) Signed-off-by: Matthieu MOREL --- container_file_test.go | 6 +- docker_files_test.go | 36 +--- docker_test.go | 184 +++++--------------- file_test.go | 36 +--- from_dockerfile_test.go | 24 +-- image_substitutors_test.go | 46 ++--- image_test.go | 6 +- lifecycle_test.go | 8 +- logconsumer_test.go | 29 +-- modules/cassandra/cassandra_test.go | 12 +- modules/dolt/dolt_test.go | 8 +- modules/elasticsearch/elasticsearch_test.go | 14 +- modules/k6/k6_test.go | 8 +- modules/neo4j/neo4j_test.go | 8 +- modules/rabbitmq/rabbitmq_test.go | 29 +-- modules/weaviate/weaviate_test.go | 20 +-- wait/exec_test.go | 20 +-- wait/exit_test.go | 5 +- wait/host_port_test.go | 50 ++---- wait/sql_test.go | 6 +- 20 files changed, 150 insertions(+), 405 deletions(-) diff --git a/container_file_test.go b/container_file_test.go index 31273c9966..166225f327 100644 --- a/container_file_test.go +++ b/container_file_test.go @@ -7,6 +7,8 @@ import ( "os" "path/filepath" "testing" + + "github.com/stretchr/testify/require" ) func TestContainerFileValidation(t *testing.T) { @@ -17,9 +19,7 @@ func TestContainerFileValidation(t *testing.T) { } f, err := os.Open(filepath.Join(".", "testdata", "hello.sh")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) testTable := []ContainerFileValidationTestCase{ { diff --git a/docker_files_test.go b/docker_files_test.go index 9b8551f325..6b32168081 100644 --- a/docker_files_test.go +++ b/docker_files_test.go @@ -21,14 +21,10 @@ func TestCopyFileToContainer(t *testing.T) { // copyFileOnCreate { absPath, err := filepath.Abs(filepath.Join(".", "testdata", "hello.sh")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) r, err := os.Open(absPath) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) ctr, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ ContainerRequest: testcontainers.ContainerRequest{ @@ -58,13 +54,9 @@ func TestCopyFileToRunningContainer(t *testing.T) { // Not using the assertations here to avoid leaking the library into the example // copyFileAfterCreate { waitForPath, err := filepath.Abs(filepath.Join(".", "testdata", "waitForHello.sh")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) helloPath, err := filepath.Abs(filepath.Join(".", "testdata", "hello.sh")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) ctr, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ ContainerRequest: testcontainers.ContainerRequest{ @@ -100,9 +92,7 @@ func TestCopyDirectoryToContainer(t *testing.T) { // Not using the assertations here to avoid leaking the library into the example // copyDirectoryToContainer { dataDirectory, err := filepath.Abs(filepath.Join(".", "testdata")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) ctr, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ ContainerRequest: testcontainers.ContainerRequest{ @@ -133,13 +123,9 @@ func TestCopyDirectoryToRunningContainerAsFile(t *testing.T) { // copyDirectoryToRunningContainerAsFile { dataDirectory, err := filepath.Abs(filepath.Join(".", "testdata")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) waitForPath, err := filepath.Abs(filepath.Join(dataDirectory, "waitForHello.sh")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) ctr, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ ContainerRequest: testcontainers.ContainerRequest{ @@ -175,13 +161,9 @@ func TestCopyDirectoryToRunningContainerAsDir(t *testing.T) { // Not using the assertations here to avoid leaking the library into the example // copyDirectoryToRunningContainerAsDir { waitForPath, err := filepath.Abs(filepath.Join(".", "testdata", "waitForHello.sh")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) dataDirectory, err := filepath.Abs(filepath.Join(".", "testdata")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) ctr, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ ContainerRequest: testcontainers.ContainerRequest{ diff --git a/docker_test.go b/docker_test.go index 2cc762a6aa..a9fcbd03d6 100644 --- a/docker_test.go +++ b/docker_test.go @@ -55,9 +55,7 @@ func TestContainerWithHostNetworkOptions(t *testing.T) { SkipIfDockerDesktop(t, ctx) absPath, err := filepath.Abs(filepath.Join("testdata", "nginx-highport.conf")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) gcr := GenericContainerRequest{ ProviderType: providerType, @@ -114,9 +112,7 @@ func TestContainerWithHostNetworkOptions_UseExposePortsFromImageConfigs(t *testi nginxC, err := GenericContainer(ctx, gcr) CleanupContainer(t, nginxC) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) endpoint, err := nginxC.Endpoint(ctx, "http") if err != nil { @@ -124,9 +120,7 @@ func TestContainerWithHostNetworkOptions_UseExposePortsFromImageConfigs(t *testi } resp, err := http.Get(endpoint) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { @@ -173,9 +167,7 @@ func TestContainerWithHostNetwork(t *testing.T) { SkipIfDockerDesktop(t, ctx) absPath, err := filepath.Abs(filepath.Join("testdata", "nginx-highport.conf")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) gcr := GenericContainerRequest{ ProviderType: providerType, @@ -334,9 +326,7 @@ func TestContainerTerminationRemovesDockerImage(t *testing.T) { t.Run("if not built from Dockerfile", func(t *testing.T) { ctx := context.Background() dockerClient, err := NewDockerClientWithOpts(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer dockerClient.Close() ctr, err := GenericContainer(ctx, GenericContainerRequest{ @@ -364,9 +354,7 @@ func TestContainerTerminationRemovesDockerImage(t *testing.T) { t.Run("if built from Dockerfile", func(t *testing.T) { ctx := context.Background() dockerClient, err := NewDockerClientWithOpts(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer dockerClient.Close() req := ContainerRequest{ @@ -382,20 +370,14 @@ func TestContainerTerminationRemovesDockerImage(t *testing.T) { Started: true, }) CleanupContainer(t, ctr) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) containerID := ctr.GetContainerID() resp, err := dockerClient.ContainerInspect(ctx, containerID) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) imageID := resp.Config.Image err = ctr.Terminate(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) _, _, err = dockerClient.ImageInspectWithRaw(ctx, imageID) if err == nil { @@ -438,9 +420,7 @@ func TestTwoContainersExposingTheSamePort(t *testing.T) { require.NoError(t, err) resp, err := http.Get(endpointA) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { @@ -448,14 +428,10 @@ func TestTwoContainersExposingTheSamePort(t *testing.T) { } endpointB, err := nginxB.PortEndpoint(ctx, nginxDefaultPort, "http") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) resp, err = http.Get(endpointB) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { @@ -484,25 +460,19 @@ func TestContainerCreation(t *testing.T) { require.NoError(t, err) resp, err := http.Get(endpoint) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { t.Errorf("Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode) } networkIP, err := nginxC.ContainerIP(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if len(networkIP) == 0 { t.Errorf("Expected an IP address, got %v", networkIP) } networkAliases, err := nginxC.NetworkAliases(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if len(networkAliases) != 1 { fmt.Printf("%v", networkAliases) t.Errorf("Expected number of connected networks %d. Got %d.", 0, len(networkAliases)) @@ -536,18 +506,14 @@ func TestContainerCreationWithName(t *testing.T) { require.NoError(t, err) inspect, err := nginxC.Inspect(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) name := inspect.Name if name != expectedName { t.Errorf("Expected container name '%s'. Got '%s'.", expectedName, name) } networks, err := nginxC.Networks(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if len(networks) != 1 { t.Errorf("Expected networks 1. Got '%d'.", len(networks)) } @@ -567,9 +533,7 @@ func TestContainerCreationWithName(t *testing.T) { require.NoError(t, err) resp, err := http.Get(endpoint) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { @@ -596,13 +560,9 @@ func TestContainerCreationAndWaitForListeningPortLongEnough(t *testing.T) { require.NoError(t, err) origin, err := nginxC.PortEndpoint(ctx, nginxDefaultPort, "http") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) resp, err := http.Get(origin) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { @@ -649,13 +609,9 @@ func TestContainerRespondsWithHttp200ForIndex(t *testing.T) { require.NoError(t, err) origin, err := nginxC.PortEndpoint(ctx, nginxDefaultPort, "http") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) resp, err := http.Get(origin) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer resp.Body.Close() if resp.StatusCode != http.StatusOK { @@ -1134,9 +1090,7 @@ func ExampleContainer_MappedPort() { func TestContainerCreationWithVolumeAndFileWritingToIt(t *testing.T) { absPath, err := filepath.Abs(filepath.Join(".", "testdata", "hello.sh")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) ctx, cnl := context.WithTimeout(context.Background(), 30*time.Second) defer cnl() @@ -1184,18 +1138,14 @@ func TestContainerWithTmpFs(t *testing.T) { // exec_reader_example { c, reader, err := ctr.Exec(ctx, []string{"ls", path}) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if c != 1 { t.Fatalf("File %s should not have existed, expected return code 1, got %v", path, c) } buf := new(strings.Builder) _, err = io.Copy(buf, reader) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) // See the logs from the command execution. t.Log(buf.String()) @@ -1203,18 +1153,14 @@ func TestContainerWithTmpFs(t *testing.T) { // exec_example { c, _, err = ctr.Exec(ctx, []string{"touch", path}) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if c != 0 { t.Fatalf("File %s should have been created successfully, expected return code 0, got %v", path, c) } // } c, _, err = ctr.Exec(ctx, []string{"ls", path}) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if c != 0 { t.Fatalf("File %s should exist, expected return code 0, got %v", path, c) } @@ -1393,9 +1339,7 @@ func TestDockerContainerCopyFileToContainer(t *testing.T) { _ = nginxC.CopyFileToContainer(ctx, filepath.Join(".", "testdata", "hello.sh"), tc.copiedFileName, 700) c, _, err := nginxC.Exec(ctx, []string{"bash", tc.copiedFileName}) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if c != 0 { t.Fatalf("File %s should exist, expected return code 0, got %v", tc.copiedFileName, c) } @@ -1424,9 +1368,7 @@ func TestDockerContainerCopyDirToContainer(t *testing.T) { p = filepath.Join(".", "testdata") err = nginxC.CopyDirToContainer(ctx, p, "/tmp/testdata", 700) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) assertExtractedFiles(t, ctx, nginxC, p, "/tmp/testdata/") } @@ -1604,17 +1546,11 @@ func TestDockerContainerCopyToContainer(t *testing.T) { require.NoError(t, err) fileContent, err := os.ReadFile(filepath.Join(".", "testdata", "hello.sh")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) err = nginxC.CopyToContainer(ctx, fileContent, tc.copiedFileName, 700) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) c, _, err := nginxC.Exec(ctx, []string{"bash", tc.copiedFileName}) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if c != 0 { t.Fatalf("File %s should exist, expected return code 0, got %v", tc.copiedFileName, c) } @@ -1624,9 +1560,7 @@ func TestDockerContainerCopyToContainer(t *testing.T) { func TestDockerContainerCopyFileFromContainer(t *testing.T) { fileContent, err := os.ReadFile(filepath.Join(".", "testdata", "hello.sh")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) ctx := context.Background() nginxC, err := GenericContainer(ctx, GenericContainerRequest{ @@ -1644,23 +1578,17 @@ func TestDockerContainerCopyFileFromContainer(t *testing.T) { copiedFileName := "hello_copy.sh" _ = nginxC.CopyFileToContainer(ctx, filepath.Join(".", "testdata", "hello.sh"), "/"+copiedFileName, 700) c, _, err := nginxC.Exec(ctx, []string{"bash", copiedFileName}) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if c != 0 { t.Fatalf("File %s should exist, expected return code 0, got %v", copiedFileName, c) } reader, err := nginxC.CopyFileFromContainer(ctx, "/"+copiedFileName) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer reader.Close() fileContentFromContainer, err := io.ReadAll(reader) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) assert.Equal(t, fileContent, fileContentFromContainer) } @@ -1682,23 +1610,17 @@ func TestDockerContainerCopyEmptyFileFromContainer(t *testing.T) { copiedFileName := "hello_copy.sh" _ = nginxC.CopyFileToContainer(ctx, filepath.Join(".", "testdata", "empty.sh"), "/"+copiedFileName, 700) c, _, err := nginxC.Exec(ctx, []string{"bash", copiedFileName}) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if c != 0 { t.Fatalf("File %s should exist, expected return code 0, got %v", copiedFileName, c) } reader, err := nginxC.CopyFileFromContainer(ctx, "/"+copiedFileName) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer reader.Close() fileContentFromContainer, err := io.ReadAll(reader) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) require.Empty(t, fileContentFromContainer) } @@ -1809,9 +1731,7 @@ func TestContainerRunningCheckingStatusCode(t *testing.T) { Started: true, }) CleanupContainer(t, influx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) } func TestContainerWithUserID(t *testing.T) { @@ -1831,14 +1751,10 @@ func TestContainerWithUserID(t *testing.T) { require.NoError(t, err) r, err := ctr.Logs(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer r.Close() b, err := io.ReadAll(r) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) actual := regexp.MustCompile(`\D+`).ReplaceAllString(string(b), "") assert.Equal(t, req.User, actual) } @@ -1859,14 +1775,10 @@ func TestContainerWithNoUserID(t *testing.T) { require.NoError(t, err) r, err := ctr.Logs(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer r.Close() b, err := io.ReadAll(r) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) actual := regexp.MustCompile(`\D+`).ReplaceAllString(string(b), "") assert.Equal(t, "0", actual) } @@ -1875,15 +1787,11 @@ func TestGetGatewayIP(t *testing.T) { // When using docker compose with DinD mode, and using host port or http wait strategy // It's need to invoke GetGatewayIP for get the host provider, err := providerType.GetProvider(WithLogger(TestLogger(t))) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer provider.Close() ip, err := provider.(*DockerProvider).GetGatewayIP(context.Background()) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if ip == "" { t.Fatal("could not get gateway ip") } diff --git a/file_test.go b/file_test.go index 1128304df7..06ef8905e7 100644 --- a/file_test.go +++ b/file_test.go @@ -78,34 +78,24 @@ func Test_TarDir(t *testing.T) { } buff, err := tarDir(src, 0o755) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) tmpDir := filepath.Join(t.TempDir(), "subfolder") err = untar(tmpDir, bytes.NewReader(buff.Bytes())) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) srcFiles, err := os.ReadDir(src) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) for _, srcFile := range srcFiles { if srcFile.IsDir() { continue } srcBytes, err := os.ReadFile(filepath.Join(src, srcFile.Name())) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) untarBytes, err := os.ReadFile(filepath.Join(tmpDir, "testdata", srcFile.Name())) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) assert.Equal(t, srcBytes, untarBytes) } }) @@ -114,28 +104,20 @@ func Test_TarDir(t *testing.T) { func Test_TarFile(t *testing.T) { b, err := os.ReadFile(filepath.Join(".", "testdata", "Dockerfile")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) buff, err := tarFile("Docker.file", func(tw io.Writer) error { _, err := tw.Write(b) return err }, int64(len(b)), 0o755) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) tmpDir := t.TempDir() err = untar(tmpDir, bytes.NewReader(buff.Bytes())) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) untarBytes, err := os.ReadFile(filepath.Join(tmpDir, "Docker.file")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) assert.Equal(t, b, untarBytes) } diff --git a/from_dockerfile_test.go b/from_dockerfile_test.go index 854492fbfd..75f80537d2 100644 --- a/from_dockerfile_test.go +++ b/from_dockerfile_test.go @@ -17,9 +17,7 @@ import ( func TestBuildImageFromDockerfile(t *testing.T) { provider, err := NewDockerProvider() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer provider.Close() cli := provider.Client() @@ -47,17 +45,13 @@ func TestBuildImageFromDockerfile(t *testing.T) { Force: true, PruneChildren: true, }) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) }) } func TestBuildImageFromDockerfile_NoRepo(t *testing.T) { provider, err := NewDockerProvider() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer provider.Close() cli := provider.Client() @@ -82,9 +76,7 @@ func TestBuildImageFromDockerfile_NoRepo(t *testing.T) { Force: true, PruneChildren: true, }) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) }) } @@ -112,9 +104,7 @@ func TestBuildImageFromDockerfile_BuildError(t *testing.T) { func TestBuildImageFromDockerfile_NoTag(t *testing.T) { provider, err := NewDockerProvider() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer provider.Close() cli := provider.Client() @@ -139,9 +129,7 @@ func TestBuildImageFromDockerfile_NoTag(t *testing.T) { Force: true, PruneChildren: true, }) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) }) } diff --git a/image_substitutors_test.go b/image_substitutors_test.go index 92b42e63b3..4a168254e6 100644 --- a/image_substitutors_test.go +++ b/image_substitutors_test.go @@ -4,6 +4,8 @@ import ( "context" "testing" + "github.com/stretchr/testify/require" + "github.com/testcontainers/testcontainers-go/internal/config" ) @@ -12,9 +14,7 @@ func TestCustomHubSubstitutor(t *testing.T) { s := NewCustomHubSubstitutor("quay.io") img, err := s.Substitute("foo/foo:latest") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if img != "quay.io/foo/foo:latest" { t.Errorf("expected quay.io/foo/foo:latest, got %s", img) @@ -24,9 +24,7 @@ func TestCustomHubSubstitutor(t *testing.T) { s := NewCustomHubSubstitutor("quay.io") img, err := s.Substitute("quay.io/foo/foo:latest") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if img != "quay.io/foo/foo:latest" { t.Errorf("expected quay.io/foo/foo:latest, got %s", img) @@ -39,9 +37,7 @@ func TestCustomHubSubstitutor(t *testing.T) { s := NewCustomHubSubstitutor("quay.io") img, err := s.Substitute("foo/foo:latest") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if img != "foo/foo:latest" { t.Errorf("expected foo/foo:latest, got %s", img) @@ -55,9 +51,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { s := newPrependHubRegistry("my-registry") img, err := s.Substitute("foo:latest") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if img != "my-registry/foo:latest" { t.Errorf("expected my-registry/foo, got %s", img) @@ -67,9 +61,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { s := newPrependHubRegistry("my-registry") img, err := s.Substitute("user/foo:latest") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if img != "my-registry/user/foo:latest" { t.Errorf("expected my-registry/foo, got %s", img) @@ -80,9 +72,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { s := newPrependHubRegistry("my-registry") img, err := s.Substitute("org/user/foo:latest") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if img != "my-registry/org/user/foo:latest" { t.Errorf("expected my-registry/org/foo:latest, got %s", img) @@ -95,9 +85,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { s := newPrependHubRegistry("my-registry") img, err := s.Substitute("quay.io/foo:latest") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if img != "quay.io/foo:latest" { t.Errorf("expected quay.io/foo:latest, got %s", img) @@ -108,9 +96,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { s := newPrependHubRegistry("my-registry") img, err := s.Substitute("registry.hub.docker.com/library/foo:latest") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if img != "registry.hub.docker.com/library/foo:latest" { t.Errorf("expected registry.hub.docker.com/library/foo:latest, got %s", img) @@ -121,9 +107,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { s := newPrependHubRegistry("my-registry") img, err := s.Substitute("registry.hub.docker.com/foo:latest") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if img != "registry.hub.docker.com/foo:latest" { t.Errorf("expected registry.hub.docker.com/foo:latest, got %s", img) @@ -150,14 +134,10 @@ func TestSubstituteBuiltImage(t *testing.T) { config.Reset() c, err := GenericContainer(context.Background(), req) CleanupContainer(t, c) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) json, err := c.Inspect(context.Background()) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if json.Config.Image != "my-registry/my-repo:my-image" { t.Errorf("expected my-registry/my-repo:my-image, got %s", json.Config.Image) diff --git a/image_test.go b/image_test.go index 2344c5063d..39f8134acd 100644 --- a/image_test.go +++ b/image_test.go @@ -6,6 +6,8 @@ import ( "path/filepath" "testing" + "github.com/stretchr/testify/require" + "github.com/testcontainers/testcontainers-go/internal/core" ) @@ -79,9 +81,7 @@ func TestSaveImages(t *testing.T) { } info, err := os.Stat(output) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if info.Size() == 0 { t.Fatalf("output file is empty") diff --git a/lifecycle_test.go b/lifecycle_test.go index 0d7e9c7861..374d45bf80 100644 --- a/lifecycle_test.go +++ b/lifecycle_test.go @@ -904,14 +904,10 @@ func TestPrintContainerLogsOnError(t *testing.T) { }) CleanupContainer(t, ctr) // it should fail because the waiting for condition is not met - if err == nil { - t.Fatal(err) - } + require.Error(t, err) containerLogs, err := ctr.Logs(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer containerLogs.Close() // read container logs line by line, checking that each line is present in the stdout diff --git a/logconsumer_test.go b/logconsumer_test.go index f16c2fc007..e4ee916e0f 100644 --- a/logconsumer_test.go +++ b/logconsumer_test.go @@ -285,9 +285,7 @@ func TestContainerLogWithErrClosed(t *testing.T) { opts := []client.Opt{client.WithHost(remoteDocker), client.WithAPIVersionNegotiation()} dockerClient, err := NewDockerClientWithOpts(ctx, opts...) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer dockerClient.Close() provider := &DockerProvider{ @@ -313,18 +311,13 @@ func TestContainerLogWithErrClosed(t *testing.T) { Consumers: []LogConsumer{&consumer}, }, }) - if err != nil { - t.Fatal(err) - } - if err := nginx.Start(ctx); err != nil { - t.Fatal(err) - } + require.NoError(t, err) + err = nginx.Start(ctx) + require.NoError(t, err) CleanupContainer(t, nginx) port, err := nginx.MappedPort(ctx, "80/tcp") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) // Gather the initial container logs time.Sleep(time.Second * 1) @@ -384,19 +377,13 @@ func TestContainerLogsShouldBeWithoutStreamHeader(t *testing.T) { Started: true, }) CleanupContainer(t, ctr) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) r, err := ctr.Logs(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer r.Close() b, err := io.ReadAll(r) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) assert.Equal(t, "0", strings.TrimSpace(string(b))) } diff --git a/modules/cassandra/cassandra_test.go b/modules/cassandra/cassandra_test.go index 3c8cd1e918..f4979dff5f 100644 --- a/modules/cassandra/cassandra_test.go +++ b/modules/cassandra/cassandra_test.go @@ -62,9 +62,7 @@ func TestCassandraWithConfigFile(t *testing.T) { cluster := gocql.NewCluster(connectionHost) session, err := cluster.CreateSession() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer session.Close() var result string @@ -90,9 +88,7 @@ func TestCassandraWithInitScripts(t *testing.T) { cluster := gocql.NewCluster(connectionHost) session, err := cluster.CreateSession() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer session.Close() var test Test @@ -113,9 +109,7 @@ func TestCassandraWithInitScripts(t *testing.T) { cluster := gocql.NewCluster(connectionHost) session, err := cluster.CreateSession() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer session.Close() var test Test diff --git a/modules/dolt/dolt_test.go b/modules/dolt/dolt_test.go index b239136e38..a1e46cc976 100644 --- a/modules/dolt/dolt_test.go +++ b/modules/dolt/dolt_test.go @@ -72,14 +72,10 @@ func TestDoltWithPublicRemoteCloneUrl(t *testing.T) { func createTestCredsFile(t *testing.T) string { t.Helper() file, err := os.CreateTemp(t.TempDir(), "prefix") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer file.Close() _, err = file.WriteString("some-fake-creds") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) return file.Name() } diff --git a/modules/elasticsearch/elasticsearch_test.go b/modules/elasticsearch/elasticsearch_test.go index 69c4149fc4..fdfe636769 100644 --- a/modules/elasticsearch/elasticsearch_test.go +++ b/modules/elasticsearch/elasticsearch_test.go @@ -138,9 +138,8 @@ func TestElasticsearch(t *testing.T) { } var esResp ElasticsearchResponse - if err := json.NewDecoder(resp.Body).Decode(&esResp); err != nil { - t.Fatal(err) - } + 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) @@ -203,9 +202,7 @@ func TestElasticsearch8WithoutCredentials(t *testing.T) { httpClient := configureHTTPClient(ctr) req, err := http.NewRequest("GET", ctr.Settings.Address, nil) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) // elastic:changeme are the default credentials for Elasticsearch 8 req.SetBasicAuth(ctr.Settings.Username, ctr.Settings.Password) @@ -218,9 +215,8 @@ func TestElasticsearch8WithoutCredentials(t *testing.T) { defer resp.Body.Close() var esResp ElasticsearchResponse - if err := json.NewDecoder(resp.Body).Decode(&esResp); err != nil { - t.Fatal(err) - } + 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) diff --git a/modules/k6/k6_test.go b/modules/k6/k6_test.go index f2cc39ef72..bc40bd13a6 100644 --- a/modules/k6/k6_test.go +++ b/modules/k6/k6_test.go @@ -63,16 +63,12 @@ func TestK6(t *testing.T) { var options testcontainers.CustomizeRequestOption if !strings.HasPrefix(tc.script, "http") { absPath, err := filepath.Abs(filepath.Join("scripts", tc.script)) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) options = k6.WithTestScript(absPath) } else { uri, err := url.Parse(tc.script) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) desc := k6.DownloadableFile{Uri: *uri, DownloadDir: t.TempDir()} options = k6.WithRemoteTestScript(desc) diff --git a/modules/neo4j/neo4j_test.go b/modules/neo4j/neo4j_test.go index 9d41e4afe5..a5cff51182 100644 --- a/modules/neo4j/neo4j_test.go +++ b/modules/neo4j/neo4j_test.go @@ -167,13 +167,9 @@ func createDriver(t *testing.T, ctx context.Context, container *neo4j.Neo4jConta // boltURL { boltUrl, err := container.BoltUrl(ctx) // } - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) driver, err := neo.NewDriverWithContext(boltUrl, neo.BasicAuth("neo4j", testPassword, "")) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) t.Cleanup(func() { if err := driver.Close(ctx); err != nil { t.Fatalf("failed to close neo: %s", err) diff --git a/modules/rabbitmq/rabbitmq_test.go b/modules/rabbitmq/rabbitmq_test.go index f0b82ca2db..6c4cca0c8c 100644 --- a/modules/rabbitmq/rabbitmq_test.go +++ b/modules/rabbitmq/rabbitmq_test.go @@ -93,9 +93,8 @@ func TestRunContainer_connectUsingAmqps(t *testing.T) { if amqpsConnection.IsClosed() { t.Fatal(fmt.Errorf("AMQPS Connection unexpectdely closed")) } - if err = amqpsConnection.Close(); err != nil { - t.Fatal(err) - } + err = amqpsConnection.Close() + require.NoError(t, err) } func TestRunContainer_withAllSettings(t *testing.T) { @@ -248,14 +247,10 @@ func assertEntity(t *testing.T, container testcontainers.Container, listCommand cmd := []string{"rabbitmqadmin", "list", listCommand} _, out, err := container.Exec(ctx, cmd) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) check, err := io.ReadAll(out) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) for _, e := range entities { if !strings.Contains(string(check), e) { @@ -277,14 +272,10 @@ func assertEntityWithVHost(t *testing.T, container testcontainers.Container, lis } _, out, err := container.Exec(ctx, cmd) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) check, err := io.ReadAll(out) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) for _, e := range entities { if !strings.Contains(string(check), e) { @@ -303,14 +294,10 @@ func assertPluginIsEnabled(t *testing.T, container testcontainers.Container, plu for _, plugin := range plugins { _, out, err := container.Exec(ctx, []string{"rabbitmq-plugins", "is_enabled", plugin}) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) check, err := io.ReadAll(out) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if !strings.Contains(string(check), plugin+" is enabled") { return false diff --git a/modules/weaviate/weaviate_test.go b/modules/weaviate/weaviate_test.go index d6dae679e6..faf8e42f92 100644 --- a/modules/weaviate/weaviate_test.go +++ b/modules/weaviate/weaviate_test.go @@ -42,9 +42,7 @@ func TestWeaviate(t *testing.T) { // gRPCHostAddress { host, err := ctr.GrpcHostAddress(ctx) // } - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) var opts []grpc.DialOption @@ -65,22 +63,14 @@ func TestWeaviate(t *testing.T) { t.Run("Weaviate client", func(tt *testing.T) { httpScheme, httpHost, err := ctr.HttpHostAddress(ctx) - if err != nil { - tt.Fatal(err) - } + require.NoError(tt, err) grpcHost, err := ctr.GrpcHostAddress(ctx) - if err != nil { - tt.Fatal(err) - } + require.NoError(tt, err) config := wvt.Config{Scheme: httpScheme, Host: httpHost, GrpcConfig: &wvtgrpc.Config{Host: grpcHost}} client, err := wvt.NewClient(config) - if err != nil { - tt.Fatal(err) - } + require.NoError(tt, err) meta, err := client.Misc().MetaGetter().Do(ctx) - if err != nil { - tt.Fatal(err) - } + require.NoError(tt, err) if meta == nil || meta.Version == "" { tt.Fatal("failed to get /v1/meta response") diff --git a/wait/exec_test.go b/wait/exec_test.go index 4d2d97c51d..ab84fabd17 100644 --- a/wait/exec_test.go +++ b/wait/exec_test.go @@ -114,18 +114,14 @@ func TestExecStrategyWaitUntilReady(t *testing.T) { wg := wait.NewExecStrategy([]string{"true"}). WithStartupTimeout(30 * time.Second) err := wg.WaitUntilReady(context.Background(), target) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) } func TestExecStrategyWaitUntilReadyForExec(t *testing.T) { target := mockExecTarget{} wg := wait.ForExec([]string{"true"}) err := wg.WaitUntilReady(context.Background(), target) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) } func TestExecStrategyWaitUntilReady_MultipleChecks(t *testing.T) { @@ -136,9 +132,7 @@ func TestExecStrategyWaitUntilReady_MultipleChecks(t *testing.T) { wg := wait.NewExecStrategy([]string{"true"}). WithPollInterval(500 * time.Millisecond) err := wg.WaitUntilReady(context.Background(), target) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) } func TestExecStrategyWaitUntilReady_DeadlineExceeded(t *testing.T) { @@ -163,9 +157,7 @@ func TestExecStrategyWaitUntilReady_CustomExitCode(t *testing.T) { return exitCode == 10 }) err := wg.WaitUntilReady(context.Background(), target) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) } func TestExecStrategyWaitUntilReady_withExitCode(t *testing.T) { @@ -176,9 +168,7 @@ func TestExecStrategyWaitUntilReady_withExitCode(t *testing.T) { // Default is 60. Let's shorten that wg.WithStartupTimeout(time.Second * 2) err := wg.WaitUntilReady(context.Background(), target) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) // Ensure we aren't spuriously returning on any code wg = wait.NewExecStrategy([]string{"true"}).WithExitCode(0) diff --git a/wait/exit_test.go b/wait/exit_test.go index 4795fd4ad6..5c2ec004db 100644 --- a/wait/exit_test.go +++ b/wait/exit_test.go @@ -9,6 +9,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/go-connections/nat" + "github.com/stretchr/testify/require" tcexec "github.com/testcontainers/testcontainers-go/exec" ) @@ -56,7 +57,5 @@ func TestWaitForExit(t *testing.T) { } wg := NewExitStrategy().WithExitTimeout(100 * time.Millisecond) err := wg.WaitUntilReady(context.Background(), target) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) } diff --git a/wait/host_port_test.go b/wait/host_port_test.go index 1623ef95c0..4dbaad741f 100644 --- a/wait/host_port_test.go +++ b/wait/host_port_test.go @@ -19,16 +19,12 @@ import ( func TestWaitForListeningPortSucceeds(t *testing.T) { listener, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer listener.Close() rawPort := listener.Addr().(*net.TCPAddr).Port port, err := nat.NewPort("tcp", strconv.Itoa(rawPort)) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) var mappedPortCount, execCount int target := &MockStrategyTarget{ @@ -60,23 +56,18 @@ func TestWaitForListeningPortSucceeds(t *testing.T) { WithStartupTimeout(5 * time.Second). WithPollInterval(100 * time.Millisecond) - if err := wg.WaitUntilReady(context.Background(), target); err != nil { - t.Fatal(err) - } + err = wg.WaitUntilReady(context.Background(), target) + require.NoError(t, err) } func TestWaitForExposedPortSucceeds(t *testing.T) { listener, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer listener.Close() rawPort := listener.Addr().(*net.TCPAddr).Port port, err := nat.NewPort("tcp", strconv.Itoa(rawPort)) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) var mappedPortCount, execCount int target := &MockStrategyTarget{ @@ -124,9 +115,8 @@ func TestWaitForExposedPortSucceeds(t *testing.T) { WithStartupTimeout(5 * time.Second). WithPollInterval(100 * time.Millisecond) - if err := wg.WaitUntilReady(context.Background(), target); err != nil { - t.Fatal(err) - } + err = wg.WaitUntilReady(context.Background(), target) + require.NoError(t, err) } func TestHostPortStrategyFailsWhileGettingPortDueToOOMKilledContainer(t *testing.T) { @@ -298,16 +288,12 @@ func TestHostPortStrategyFailsWhileExternalCheckingDueToUnexpectedContainerStatu func TestHostPortStrategyFailsWhileInternalCheckingDueToOOMKilledContainer(t *testing.T) { listener, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer listener.Close() rawPort := listener.Addr().(*net.TCPAddr).Port port, err := nat.NewPort("tcp", strconv.Itoa(rawPort)) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) var stateCount int target := &MockStrategyTarget{ @@ -342,16 +328,12 @@ func TestHostPortStrategyFailsWhileInternalCheckingDueToOOMKilledContainer(t *te func TestHostPortStrategyFailsWhileInternalCheckingDueToExitedContainer(t *testing.T) { listener, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer listener.Close() rawPort := listener.Addr().(*net.TCPAddr).Port port, err := nat.NewPort("tcp", strconv.Itoa(rawPort)) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) var stateCount int target := &MockStrategyTarget{ @@ -387,16 +369,12 @@ func TestHostPortStrategyFailsWhileInternalCheckingDueToExitedContainer(t *testi func TestHostPortStrategyFailsWhileInternalCheckingDueToUnexpectedContainerStatus(t *testing.T) { listener, err := net.Listen("tcp", "localhost:0") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) defer listener.Close() rawPort := listener.Addr().(*net.TCPAddr).Port port, err := nat.NewPort("tcp", strconv.Itoa(rawPort)) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) var stateCount int target := &MockStrategyTarget{ diff --git a/wait/sql_test.go b/wait/sql_test.go index 053ed965e8..2a7db5b330 100644 --- a/wait/sql_test.go +++ b/wait/sql_test.go @@ -9,6 +9,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/go-connections/nat" + "github.com/stretchr/testify/require" ) func Test_waitForSql_WithQuery(t *testing.T) { @@ -102,9 +103,8 @@ func TestWaitForSQLSucceeds(t *testing.T) { WithStartupTimeout(500 * time.Millisecond). WithPollInterval(100 * time.Millisecond) - if err := wg.WaitUntilReady(context.Background(), target); err != nil { - t.Fatal(err) - } + err := wg.WaitUntilReady(context.Background(), target) + require.NoError(t, err) } func TestWaitForSQLFailsWhileGettingPortDueToOOMKilledContainer(t *testing.T) {