From a58712db7fb0484f98421043d06b6c0838475c49 Mon Sep 17 00:00:00 2001 From: Vivek Date: Sat, 14 Sep 2024 12:07:55 +0530 Subject: [PATCH] fix: replace if-condition for error handling in tests with require.NoError()/require.Error() --- 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 | 45 ++--- image_test.go | 5 +- 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 | 15 +- modules/k6/k6_test.go | 8 +- modules/neo4j/neo4j_test.go | 8 +- modules/rabbitmq/rabbitmq_test.go | 29 +-- modules/weaviate/weaviate_test.go | 20 +-- reaper_test.go | 28 +-- wait/exec_test.go | 20 +-- wait/exit_test.go | 5 +- wait/host_port_test.go | 66 ++----- wait/sql_test.go | 6 +- 21 files changed, 159 insertions(+), 439 deletions(-) diff --git a/container_file_test.go b/container_file_test.go index 31273c9966a..166225f3272 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 6a767e61637..3a73041c9d8 100644 --- a/docker_files_test.go +++ b/docker_files_test.go @@ -19,14 +19,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{ @@ -56,13 +52,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{ @@ -98,9 +90,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{ @@ -131,13 +121,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{ @@ -173,13 +159,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 fdc3196daec..a13caec1dbb 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, @@ -319,9 +311,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{ @@ -349,9 +339,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{ @@ -367,20 +355,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 { @@ -423,9 +405,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 { @@ -433,14 +413,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 { @@ -469,25 +445,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)) @@ -521,18 +491,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)) } @@ -552,9 +518,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 { @@ -581,13 +545,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 { @@ -634,13 +594,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 { @@ -1121,9 +1077,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() @@ -1171,18 +1125,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()) @@ -1190,18 +1140,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) } @@ -1379,9 +1325,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) } @@ -1410,9 +1354,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/") } @@ -1590,17 +1532,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) } @@ -1610,9 +1546,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{ @@ -1630,23 +1564,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) } @@ -1668,23 +1596,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) assert.Empty(t, fileContentFromContainer) } @@ -1795,9 +1717,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) { @@ -1817,14 +1737,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) } @@ -1845,14 +1761,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) } @@ -1861,15 +1773,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 1128304df7e..06ef8905e74 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 f6f7512ae3e..5b82a4e3248 100644 --- a/from_dockerfile_test.go +++ b/from_dockerfile_test.go @@ -18,9 +18,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() @@ -48,17 +46,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() @@ -83,9 +77,7 @@ func TestBuildImageFromDockerfile_NoRepo(t *testing.T) { Force: true, PruneChildren: true, }) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) }) } @@ -113,9 +105,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() @@ -140,9 +130,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 4a41f31ce67..64811c67f8c 100644 --- a/image_substitutors_test.go +++ b/image_substitutors_test.go @@ -4,6 +4,7 @@ import ( "context" "testing" + "github.com/stretchr/testify/require" "github.com/testcontainers/testcontainers-go/internal/config" ) @@ -12,9 +13,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 +23,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 +36,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 +50,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 +60,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 +71,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 +84,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 +95,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { s := newPrependHubRegistry("my-registry") img, err := s.Substitute("docker.io/foo:latest") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if img != "docker.io/foo:latest" { t.Errorf("expected docker.io/foo:latest, got %s", img) @@ -121,9 +106,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 +133,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 2344c5063d0..5eb67e030b8 100644 --- a/image_test.go +++ b/image_test.go @@ -6,6 +6,7 @@ import ( "path/filepath" "testing" + "github.com/stretchr/testify/require" "github.com/testcontainers/testcontainers-go/internal/core" ) @@ -79,9 +80,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 66c4ad8a8ae..787fa343c33 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 855a849914e..51a55fba17c 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 3c8cd1e9184..f4979dff5ff 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 61787e237b6..0a2d2c69151 100644 --- a/modules/dolt/dolt_test.go +++ b/modules/dolt/dolt_test.go @@ -71,14 +71,10 @@ func TestDoltWithPublicRemoteCloneUrl(t *testing.T) { func createTestCredsFile(t *testing.T) string { 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 69c4149fc4c..64ab76cb973 100644 --- a/modules/elasticsearch/elasticsearch_test.go +++ b/modules/elasticsearch/elasticsearch_test.go @@ -138,10 +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) } else if tt.image == baseImage8 && esResp.Version.Number != "8.9.0" { @@ -203,9 +201,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 +214,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) - } + 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 f2cc39ef72d..bc40bd13a6f 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 466bd3ddf78..69b9ca51d29 100644 --- a/modules/neo4j/neo4j_test.go +++ b/modules/neo4j/neo4j_test.go @@ -166,13 +166,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 f0b82ca2db1..6c4cca0c8c0 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 d6dae679e61..faf8e42f929 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/reaper_test.go b/reaper_test.go index f421c2686d4..7697f140de9 100644 --- a/reaper_test.go +++ b/reaper_test.go @@ -163,9 +163,7 @@ func TestContainerStartsWithTheReaper(t *testing.T) { Started: true, }) CleanupContainer(t, c) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) sessionID := core.SessionID() @@ -201,22 +199,16 @@ func TestContainerStopWithReaper(t *testing.T) { require.NoError(t, err) state, err := nginxA.State(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if state.Running != true { t.Fatal("The container shoud be in running state") } stopTimeout := 10 * time.Second err = nginxA.Stop(ctx, &stopTimeout) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) state, err = nginxA.State(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if state.Running != false { t.Fatal("The container shoud not be running") } @@ -278,21 +270,15 @@ func TestContainerTerminationWithoutReaper(t *testing.T) { Started: true, }) CleanupContainer(t, nginxA) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) state, err := nginxA.State(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) if state.Running != true { t.Fatal("The container shoud be in running state") } err = nginxA.Terminate(ctx) - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) _, err = nginxA.State(ctx) if err == nil { diff --git a/wait/exec_test.go b/wait/exec_test.go index 224f7d99d95..e3c3d738512 100644 --- a/wait/exec_test.go +++ b/wait/exec_test.go @@ -113,18 +113,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) { @@ -135,9 +131,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) { @@ -162,9 +156,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) { @@ -175,9 +167,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 4795fd4ad64..5c2ec004dba 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 1186ba7d430..43085c48e69 100644 --- a/wait/host_port_test.go +++ b/wait/host_port_test.go @@ -17,16 +17,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{ @@ -58,23 +54,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{ @@ -122,9 +113,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) { @@ -314,16 +304,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{ @@ -361,16 +347,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{ @@ -409,16 +391,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{ @@ -456,16 +434,12 @@ func TestHostPortStrategyFailsWhileInternalCheckingDueToUnexpectedContainerStatu func TestHostPortStrategySucceedsGivenShellIsNotInstalled(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) target := &MockStrategyTarget{ HostImpl: func(_ context.Context) (string, error) { @@ -511,16 +485,12 @@ func TestHostPortStrategySucceedsGivenShellIsNotInstalled(t *testing.T) { func TestHostPortStrategySucceedsGivenShellIsNotFound(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) target := &MockStrategyTarget{ HostImpl: func(_ context.Context) (string, error) { diff --git a/wait/sql_test.go b/wait/sql_test.go index 053ed965e80..2a7db5b3302 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) {