From 19c126815308937a534bc7dd31b2a4f1a113f116 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Sun, 3 Nov 2024 11:13:29 +0100 Subject: [PATCH] chore: use testify instead of t.Error (#2871) Switch to using testify require instead of manual comparisons and t.Error to simplify and make tests more consistent. Signed-off-by: Matthieu MOREL Co-authored-by: Steven Hartland --- container_file_test.go | 20 ++--- container_test.go | 30 +++----- docker_test.go | 110 +++++++--------------------- image_substitutors_test.go | 40 +++------- internal/config/config_test.go | 6 +- internal/core/docker_host_test.go | 6 +- modules/couchbase/couchbase_test.go | 6 +- modules/postgres/postgres_test.go | 4 +- provider_test.go | 10 +-- testcontainers_test.go | 26 ++----- wait/all_test.go | 9 ++- wait/http_test.go | 15 +--- 12 files changed, 82 insertions(+), 200 deletions(-) diff --git a/container_file_test.go b/container_file_test.go index 166225f327..12d2240604 100644 --- a/container_file_test.go +++ b/container_file_test.go @@ -3,7 +3,6 @@ package testcontainers import ( - "errors" "os" "path/filepath" "testing" @@ -14,7 +13,7 @@ import ( func TestContainerFileValidation(t *testing.T) { type ContainerFileValidationTestCase struct { Name string - ExpectedError error + ExpectedError string File ContainerFile } @@ -38,7 +37,7 @@ func TestContainerFileValidation(t *testing.T) { }, { Name: "invalid container file", - ExpectedError: errors.New("either HostFilePath or Reader must be specified"), + ExpectedError: "either HostFilePath or Reader must be specified", File: ContainerFile{ HostFilePath: "", Reader: nil, @@ -47,7 +46,7 @@ func TestContainerFileValidation(t *testing.T) { }, { Name: "invalid container file", - ExpectedError: errors.New("ContainerFilePath must be specified"), + ExpectedError: "ContainerFilePath must be specified", File: ContainerFile{ HostFilePath: "/path/to/host", ContainerFilePath: "", @@ -58,15 +57,10 @@ func TestContainerFileValidation(t *testing.T) { for _, testCase := range testTable { t.Run(testCase.Name, func(t *testing.T) { err := testCase.File.validate() - switch { - case err == nil && testCase.ExpectedError == nil: - return - case err == nil && testCase.ExpectedError != nil: - t.Errorf("did not receive expected error: %s", testCase.ExpectedError.Error()) - case err != nil && testCase.ExpectedError == nil: - t.Errorf("received unexpected error: %s", err.Error()) - case err.Error() != testCase.ExpectedError.Error(): - t.Errorf("errors mismatch: %s != %s", err.Error(), testCase.ExpectedError.Error()) + if testCase.ExpectedError != "" { + require.EqualError(t, err, testCase.ExpectedError) + } else { + require.NoError(t, err) } }) } diff --git a/container_test.go b/container_test.go index 632ede9d26..c3581a379e 100644 --- a/container_test.go +++ b/container_test.go @@ -23,14 +23,14 @@ import ( func Test_ContainerValidation(t *testing.T) { type ContainerValidationTestCase struct { Name string - ExpectedError error + ExpectedError string ContainerRequest testcontainers.ContainerRequest } testTable := []ContainerValidationTestCase{ { Name: "cannot set both context and image", - ExpectedError: errors.New("you cannot specify both an Image and Context in a ContainerRequest"), + ExpectedError: "you cannot specify both an Image and Context in a ContainerRequest", ContainerRequest: testcontainers.ContainerRequest{ FromDockerfile: testcontainers.FromDockerfile{ Context: ".", @@ -39,15 +39,13 @@ func Test_ContainerValidation(t *testing.T) { }, }, { - Name: "can set image without context", - ExpectedError: nil, + Name: "can set image without context", ContainerRequest: testcontainers.ContainerRequest{ Image: "redis:latest", }, }, { - Name: "can set context without image", - ExpectedError: nil, + Name: "can set context without image", ContainerRequest: testcontainers.ContainerRequest{ FromDockerfile: testcontainers.FromDockerfile{ Context: ".", @@ -55,8 +53,7 @@ func Test_ContainerValidation(t *testing.T) { }, }, { - Name: "Can mount same source to multiple targets", - ExpectedError: nil, + Name: "Can mount same source to multiple targets", ContainerRequest: testcontainers.ContainerRequest{ Image: "redis:latest", HostConfigModifier: func(hc *container.HostConfig) { @@ -66,7 +63,7 @@ func Test_ContainerValidation(t *testing.T) { }, { Name: "Cannot mount multiple sources to same target", - ExpectedError: errors.New("duplicate mount target detected: /data"), + ExpectedError: "duplicate mount target detected: /data", ContainerRequest: testcontainers.ContainerRequest{ Image: "redis:latest", HostConfigModifier: func(hc *container.HostConfig) { @@ -76,7 +73,7 @@ func Test_ContainerValidation(t *testing.T) { }, { Name: "Invalid bind mount", - ExpectedError: errors.New("invalid bind mount: /data:/data:/data"), + ExpectedError: "invalid bind mount: /data:/data:/data", ContainerRequest: testcontainers.ContainerRequest{ Image: "redis:latest", HostConfigModifier: func(hc *container.HostConfig) { @@ -89,15 +86,10 @@ func Test_ContainerValidation(t *testing.T) { for _, testCase := range testTable { t.Run(testCase.Name, func(t *testing.T) { err := testCase.ContainerRequest.Validate() - switch { - case err == nil && testCase.ExpectedError == nil: - return - case err == nil && testCase.ExpectedError != nil: - t.Errorf("did not receive expected error: %s", testCase.ExpectedError.Error()) - case err != nil && testCase.ExpectedError == nil: - t.Errorf("received unexpected error: %s", err.Error()) - case err.Error() != testCase.ExpectedError.Error(): - t.Errorf("errors mismatch: %s != %s", err.Error(), testCase.ExpectedError.Error()) + if testCase.ExpectedError != "" { + require.EqualError(t, err, testCase.ExpectedError) + } else { + require.NoError(t, err) } }) } diff --git a/docker_test.go b/docker_test.go index dc3b245d1b..3fa686632f 100644 --- a/docker_test.go +++ b/docker_test.go @@ -83,20 +83,11 @@ func TestContainerWithHostNetworkOptions(t *testing.T) { CleanupContainer(t, nginxC) require.NoError(t, err) - // host, err := nginxC.Host(ctx) - // if err != nil { - // t.Errorf("Expected host %s. Got '%d'.", host, err) - // } - // endpoint, err := nginxC.PortEndpoint(ctx, nginxHighPort, "http") - if err != nil { - t.Errorf("Expected server endpoint. Got '%v'.", err) - } + require.NoErrorf(t, err, "Expected server endpoint") _, err = http.Get(endpoint) - if err != nil { - t.Errorf("Expected OK response. Got '%d'.", err) - } + require.NoErrorf(t, err, "Expected OK response") } func TestContainerWithHostNetworkOptions_UseExposePortsFromImageConfigs(t *testing.T) { @@ -115,17 +106,13 @@ func TestContainerWithHostNetworkOptions_UseExposePortsFromImageConfigs(t *testi require.NoError(t, err) endpoint, err := nginxC.Endpoint(ctx, "http") - if err != nil { - t.Errorf("Expected server endpoint. Got '%v'.", err) - } + require.NoErrorf(t, err, "Expected server endpoint") resp, err := http.Get(endpoint) 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) - } + require.Equalf(t, http.StatusOK, resp.StatusCode, "Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode) } func TestContainerWithNetworkModeAndNetworkTogether(t *testing.T) { @@ -192,25 +179,17 @@ func TestContainerWithHostNetwork(t *testing.T) { require.NoError(t, err) portEndpoint, err := nginxC.PortEndpoint(ctx, nginxHighPort, "http") - if err != nil { - t.Errorf("Expected port endpoint %s. Got '%d'.", portEndpoint, err) - } + require.NoErrorf(t, err, "Expected port endpoint %s", portEndpoint) t.Log(portEndpoint) _, err = http.Get(portEndpoint) - if err != nil { - t.Errorf("Expected OK response. Got '%v'.", err) - } + require.NoErrorf(t, err, "Expected OK response") host, err := nginxC.Host(ctx) - if err != nil { - t.Errorf("Expected host %s. Got '%d'.", host, err) - } + require.NoErrorf(t, err, "Expected host %s", host) _, err = http.Get("http://" + host + ":8080") - if err != nil { - t.Errorf("Expected OK response. Got '%v'.", err) - } + assert.NoErrorf(t, err, "Expected OK response") } func TestContainerReturnItsContainerID(t *testing.T) { @@ -227,9 +206,7 @@ func TestContainerReturnItsContainerID(t *testing.T) { CleanupContainer(t, nginxA) require.NoError(t, err) - if nginxA.GetContainerID() == "" { - t.Errorf("expected a containerID but we got an empty string.") - } + assert.NotEmptyf(t, nginxA.GetContainerID(), "expected a containerID but we got an empty string.") } // testLogConsumer is a simple implementation of LogConsumer that logs to the test output. @@ -419,9 +396,7 @@ func TestTwoContainersExposingTheSamePort(t *testing.T) { 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) - } + require.Equalf(t, http.StatusOK, resp.StatusCode, "Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode) endpointB, err := nginxB.PortEndpoint(ctx, nginxDefaultPort, "http") require.NoError(t, err) @@ -430,9 +405,7 @@ func TestTwoContainersExposingTheSamePort(t *testing.T) { 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) - } + require.Equalf(t, http.StatusOK, resp.StatusCode, "Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode) } func TestContainerCreation(t *testing.T) { @@ -459,24 +432,15 @@ func TestContainerCreation(t *testing.T) { 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) - } + require.Equalf(t, http.StatusOK, resp.StatusCode, "Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode) networkIP, err := nginxC.ContainerIP(ctx) require.NoError(t, err) - if len(networkIP) == 0 { - t.Errorf("Expected an IP address, got %v", networkIP) - } + require.NotEmptyf(t, networkIP, "Expected an IP address, got %v", networkIP) networkAliases, err := nginxC.NetworkAliases(ctx) 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)) - } - - if len(networkAliases["bridge"]) != 0 { - t.Errorf("Expected number of aliases for 'bridge' network %d. Got %d.", 0, len(networkAliases["bridge"])) - } + require.Lenf(t, networkAliases, 1, "Expected number of connected networks %d. Got %d.", 0, len(networkAliases)) + require.Contains(t, networkAliases, "bridge") + assert.Emptyf(t, networkAliases["bridge"], "Expected number of aliases for 'bridge' network %d. Got %d.", 0, len(networkAliases["bridge"])) } func TestContainerCreationWithName(t *testing.T) { @@ -505,24 +469,16 @@ func TestContainerCreationWithName(t *testing.T) { require.NoError(t, err) name := inspect.Name - if name != expectedName { - t.Errorf("Expected container name '%s'. Got '%s'.", expectedName, name) - } + assert.Equalf(t, expectedName, name, "Expected container name '%s'. Got '%s'.", expectedName, name) networks, err := nginxC.Networks(ctx) require.NoError(t, err) - if len(networks) != 1 { - t.Errorf("Expected networks 1. Got '%d'.", len(networks)) - } + require.Lenf(t, networks, 1, "Expected networks 1. Got '%d'.", len(networks)) network := networks[0] switch providerType { case ProviderDocker: - if network != Bridge { - t.Errorf("Expected network name '%s'. Got '%s'.", Bridge, network) - } + assert.Equalf(t, Bridge, network, "Expected network name '%s'. Got '%s'.", Bridge, network) case ProviderPodman: - if network != Podman { - t.Errorf("Expected network name '%s'. Got '%s'.", Podman, network) - } + assert.Equalf(t, Podman, network, "Expected network name '%s'. Got '%s'.", Podman, network) } endpoint, err := nginxC.PortEndpoint(ctx, nginxDefaultPort, "http") @@ -532,9 +488,7 @@ func TestContainerCreationWithName(t *testing.T) { 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) - } + require.Equalf(t, http.StatusOK, resp.StatusCode, "Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode) } func TestContainerCreationAndWaitForListeningPortLongEnough(t *testing.T) { @@ -561,9 +515,7 @@ func TestContainerCreationAndWaitForListeningPortLongEnough(t *testing.T) { 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) - } + require.Equalf(t, http.StatusOK, resp.StatusCode, "Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode) } func TestContainerCreationTimesOut(t *testing.T) { @@ -582,9 +534,7 @@ func TestContainerCreationTimesOut(t *testing.T) { }) CleanupContainer(t, nginxC) - if err == nil { - t.Error("Expected timeout") - } + assert.Errorf(t, err, "Expected timeout") } func TestContainerRespondsWithHttp200ForIndex(t *testing.T) { @@ -610,9 +560,7 @@ func TestContainerRespondsWithHttp200ForIndex(t *testing.T) { 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) - } + require.Equalf(t, http.StatusOK, resp.StatusCode, "Expected status code %d. Got %d.", http.StatusOK, resp.StatusCode) } func TestContainerCreationTimesOutWithHttp(t *testing.T) { @@ -650,9 +598,7 @@ func TestContainerCreationWaitsForLogContextTimeout(t *testing.T) { Started: true, }) CleanupContainer(t, c) - if err == nil { - t.Error("Expected timeout") - } + assert.Errorf(t, err, "Expected timeout") } func TestContainerCreationWaitsForLog(t *testing.T) { @@ -755,10 +701,8 @@ func Test_BuildContainerFromDockerfileWithBuildLog(t *testing.T) { require.NoError(t, err) temp := strings.Split(string(out), "\n") - - if !regexp.MustCompile(`^Step\s*1/\d+\s*:\s*FROM alpine$`).MatchString(temp[0]) { - t.Errorf("Expected stdout first line to be %s. Got '%s'.", "Step 1/* : FROM alpine", temp[0]) - } + require.NotEmpty(t, temp) + assert.Regexpf(t, `^Step\s*1/\d+\s*:\s*FROM alpine$`, temp[0], "Expected stdout first line to be %s. Got '%s'.", "Step 1/* : FROM alpine", temp[0]) } func TestContainerCreationWaitsForLogAndPortContextTimeout(t *testing.T) { diff --git a/image_substitutors_test.go b/image_substitutors_test.go index 4a168254e6..c9d6aee244 100644 --- a/image_substitutors_test.go +++ b/image_substitutors_test.go @@ -16,9 +16,7 @@ func TestCustomHubSubstitutor(t *testing.T) { img, err := s.Substitute("foo/foo:latest") require.NoError(t, err) - if img != "quay.io/foo/foo:latest" { - t.Errorf("expected quay.io/foo/foo:latest, got %s", img) - } + require.Equalf(t, "quay.io/foo/foo:latest", img, "expected quay.io/foo/foo:latest, got %s", img) }) t.Run("should not substitute the image if it is already using the provided hub", func(t *testing.T) { s := NewCustomHubSubstitutor("quay.io") @@ -26,9 +24,7 @@ func TestCustomHubSubstitutor(t *testing.T) { img, err := s.Substitute("quay.io/foo/foo:latest") require.NoError(t, err) - if img != "quay.io/foo/foo:latest" { - t.Errorf("expected quay.io/foo/foo:latest, got %s", img) - } + require.Equalf(t, "quay.io/foo/foo:latest", img, "expected quay.io/foo/foo:latest, got %s", img) }) t.Run("should not substitute the image if hub image name prefix config exist", func(t *testing.T) { t.Cleanup(config.Reset) @@ -39,9 +35,7 @@ func TestCustomHubSubstitutor(t *testing.T) { img, err := s.Substitute("foo/foo:latest") require.NoError(t, err) - if img != "foo/foo:latest" { - t.Errorf("expected foo/foo:latest, got %s", img) - } + require.Equalf(t, "foo/foo:latest", img, "expected foo/foo:latest, got %s", img) }) } @@ -53,9 +47,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { img, err := s.Substitute("foo:latest") require.NoError(t, err) - if img != "my-registry/foo:latest" { - t.Errorf("expected my-registry/foo, got %s", img) - } + require.Equalf(t, "my-registry/foo:latest", img, "expected my-registry/foo, got %s", img) }) t.Run("image with user", func(t *testing.T) { s := newPrependHubRegistry("my-registry") @@ -63,9 +55,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { img, err := s.Substitute("user/foo:latest") require.NoError(t, err) - if img != "my-registry/user/foo:latest" { - t.Errorf("expected my-registry/foo, got %s", img) - } + require.Equalf(t, "my-registry/user/foo:latest", img, "expected my-registry/foo, got %s", img) }) t.Run("image with organization and user", func(t *testing.T) { @@ -74,9 +64,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { img, err := s.Substitute("org/user/foo:latest") require.NoError(t, err) - if img != "my-registry/org/user/foo:latest" { - t.Errorf("expected my-registry/org/foo:latest, got %s", img) - } + require.Equalf(t, "my-registry/org/user/foo:latest", img, "expected my-registry/org/foo:latest, got %s", img) }) }) @@ -87,9 +75,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { img, err := s.Substitute("quay.io/foo:latest") require.NoError(t, err) - if img != "quay.io/foo:latest" { - t.Errorf("expected quay.io/foo:latest, got %s", img) - } + require.Equalf(t, "quay.io/foo:latest", img, "expected quay.io/foo:latest, got %s", img) }) t.Run("explicitly including registry.hub.docker.com/library", func(t *testing.T) { @@ -98,9 +84,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { img, err := s.Substitute("registry.hub.docker.com/library/foo:latest") 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) - } + require.Equalf(t, "registry.hub.docker.com/library/foo:latest", img, "expected registry.hub.docker.com/library/foo:latest, got %s", img) }) t.Run("explicitly including registry.hub.docker.com", func(t *testing.T) { @@ -109,9 +93,7 @@ func TestPrependHubRegistrySubstitutor(t *testing.T) { img, err := s.Substitute("registry.hub.docker.com/foo:latest") require.NoError(t, err) - if img != "registry.hub.docker.com/foo:latest" { - t.Errorf("expected registry.hub.docker.com/foo:latest, got %s", img) - } + require.Equalf(t, "registry.hub.docker.com/foo:latest", img, "expected registry.hub.docker.com/foo:latest, got %s", img) }) }) } @@ -139,8 +121,6 @@ func TestSubstituteBuiltImage(t *testing.T) { json, err := c.Inspect(context.Background()) 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) - } + require.Equalf(t, "my-registry/my-repo:my-image", json.Config.Image, "expected my-registry/my-repo:my-image, got %s", json.Config.Image) }) } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index f1c7d3bbf3..591fcff11c 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -525,10 +525,8 @@ func TestReadTCConfig(t *testing.T) { for k, v := range tt.env { t.Setenv(k, v) } - if err := os.WriteFile(filepath.Join(tmpDir, ".testcontainers.properties"), []byte(tt.content), 0o600); err != nil { - t.Errorf("Failed to create the file: %v", err) - return - } + err := os.WriteFile(filepath.Join(tmpDir, ".testcontainers.properties"), []byte(tt.content), 0o600) + require.NoErrorf(t, err, "Failed to create the file") // config := read() diff --git a/internal/core/docker_host_test.go b/internal/core/docker_host_test.go index 41ce4f25e5..6faac45776 100644 --- a/internal/core/docker_host_test.go +++ b/internal/core/docker_host_test.go @@ -567,8 +567,6 @@ func setupTestcontainersProperties(t *testing.T, content string) { t.Setenv("HOME", homeDir) t.Setenv("USERPROFILE", homeDir) // Windows support - if err := os.WriteFile(filepath.Join(homeDir, ".testcontainers.properties"), []byte(content), 0o600); err != nil { - t.Errorf("Failed to create the file: %v", err) - return - } + err = os.WriteFile(filepath.Join(homeDir, ".testcontainers.properties"), []byte(content), 0o600) + require.NoErrorf(t, err, "Failed to create the file") } diff --git a/modules/couchbase/couchbase_test.go b/modules/couchbase/couchbase_test.go index 2e2122e01b..37f7a086a3 100644 --- a/modules/couchbase/couchbase_test.go +++ b/modules/couchbase/couchbase_test.go @@ -130,10 +130,8 @@ func testBucketUsage(t *testing.T, bucket *gocb.Bucket) { var resultData map[string]string err = result.Content(&resultData) require.NoErrorf(t, err, "could not assign content") - - if resultData["key"] != "value" { - t.Errorf("Expected value to be [%s], got %s", "value", resultData["key"]) - } + require.Contains(t, resultData, "key") + require.Equalf(t, "value", resultData["key"], "Expected value to be [%s], got %s", "value", resultData["key"]) } func connectCluster(ctx context.Context, container *tccouchbase.CouchbaseContainer) (*gocb.Cluster, error) { diff --git a/modules/postgres/postgres_test.go b/modules/postgres/postgres_test.go index 05b3f8110e..8c02e68476 100644 --- a/modules/postgres/postgres_test.go +++ b/modules/postgres/postgres_test.go @@ -75,9 +75,7 @@ func TestPostgres(t *testing.T) { require.NoError(t, err) mustConnStr := ctr.MustConnectionString(ctx, "sslmode=disable", "application_name=test") - if mustConnStr != connStr { - t.Errorf("ConnectionString was not equal to MustConnectionString") - } + require.Equalf(t, mustConnStr, connStr, "ConnectionString was not equal to MustConnectionString") // Ensure connection string is using generic format id, err := ctr.MappedPort(ctx, "5432/tcp") diff --git a/provider_test.go b/provider_test.go index e4937a49d0..94206e46bf 100644 --- a/provider_test.go +++ b/provider_test.go @@ -18,7 +18,6 @@ func TestProviderTypeGetProviderAutodetect(t *testing.T) { tr ProviderType DockerHost string want string - wantErr bool }{ { name: "default provider without podman.socket", @@ -67,15 +66,10 @@ func TestProviderTypeGetProviderAutodetect(t *testing.T) { t.Setenv("DOCKER_HOST", tt.DockerHost) got, err := tt.tr.GetProvider() - if (err != nil) != tt.wantErr { - t.Errorf("ProviderType.GetProvider() error = %v, wantErr %v", err, tt.wantErr) - return - } + require.NoErrorf(t, err, "ProviderType.GetProvider()") provider, ok := got.(*DockerProvider) require.Truef(t, ok, "ProviderType.GetProvider() = %T, want %T", got, &DockerProvider{}) - if provider.defaultBridgeNetworkName != tt.want { - t.Errorf("ProviderType.GetProvider() = %v, want %v", provider.defaultBridgeNetworkName, tt.want) - } + require.Equalf(t, tt.want, provider.defaultBridgeNetworkName, "ProviderType.GetProvider() = %v, want %v", provider.defaultBridgeNetworkName, tt.want) }) } } diff --git a/testcontainers_test.go b/testcontainers_test.go index 5ff914051c..6c06d87483 100644 --- a/testcontainers_test.go +++ b/testcontainers_test.go @@ -5,22 +5,20 @@ import ( "os/exec" "regexp" "testing" + + "github.com/stretchr/testify/require" ) func TestSessionID(t *testing.T) { t.Run("SessionID() returns a non-empty string", func(t *testing.T) { sessionID := SessionID() - if sessionID == "" { - t.Error("SessionID() returned an empty string") - } + require.NotEmptyf(t, sessionID, "SessionID() returned an empty string") }) t.Run("Multiple calls to SessionID() return the same value", func(t *testing.T) { sessionID1 := SessionID() sessionID2 := SessionID() - if sessionID1 != sessionID2 { - t.Errorf("SessionID() returned different values: %s != %s", sessionID1, sessionID2) - } + require.Equalf(t, sessionID1, sessionID2, "SessionID() returned different values: %s != %s", sessionID1, sessionID2) }) t.Run("Multiple calls to SessionID() in multiple goroutines return the same value", func(t *testing.T) { @@ -41,9 +39,7 @@ func TestSessionID(t *testing.T) { <-done <-done - if sessionID1 != sessionID2 { - t.Errorf("SessionID() returned different values: %s != %s", sessionID1, sessionID2) - } + require.Equalf(t, sessionID1, sessionID2, "SessionID() returned different values: %s != %s", sessionID1, sessionID2) }) t.Run("SessionID() from different child processes returns the same value", func(t *testing.T) { @@ -55,22 +51,16 @@ func TestSessionID(t *testing.T) { cmd1 := exec.Command("go", args...) cmd1.Env = env stdoutStderr1, err := cmd1.CombinedOutput() - if err != nil { - t.Errorf("cmd1.Run() failed with %s", err) - } + require.NoErrorf(t, err, "cmd1.Run() failed with %s", err) sessionID1 := re.FindString(string(stdoutStderr1)) cmd2 := exec.Command("go", args...) cmd2.Env = env stdoutStderr2, err := cmd2.CombinedOutput() - if err != nil { - t.Errorf("cmd2.Run() failed with %s", err) - } + require.NoErrorf(t, err, "cmd2.Run() failed with %s", err) sessionID2 := re.FindString(string(stdoutStderr2)) - if sessionID1 != sessionID2 { - t.Errorf("SessionID() returned different values: %s != %s", sessionID1, sessionID2) - } + require.Equalf(t, sessionID1, sessionID2, "SessionID() returned different values: %s != %s", sessionID1, sessionID2) }) } diff --git a/wait/all_test.go b/wait/all_test.go index 770a54f32c..87b00bb5ee 100644 --- a/wait/all_test.go +++ b/wait/all_test.go @@ -7,6 +7,8 @@ import ( "io" "testing" "time" + + "github.com/stretchr/testify/require" ) func TestMultiStrategy_WaitUntilReady(t *testing.T) { @@ -113,8 +115,11 @@ func TestMultiStrategy_WaitUntilReady(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() - if err := tt.strategy.WaitUntilReady(tt.args.ctx, tt.args.target); (err != nil) != tt.wantErr { - t.Errorf("ForAll.WaitUntilReady() error = %v, wantErr = %v", err, tt.wantErr) + err := tt.strategy.WaitUntilReady(tt.args.ctx, tt.args.target) + if tt.wantErr { + require.Error(t, err, "ForAll.WaitUntilReady()") + } else { + require.NoErrorf(t, err, "ForAll.WaitUntilReady()") } }) } diff --git a/wait/http_test.go b/wait/http_test.go index 8e30210065..32479bddd4 100644 --- a/wait/http_test.go +++ b/wait/http_test.go @@ -235,10 +235,7 @@ func TestHTTPStrategyWaitUntilReady(t *testing.T) { require.NoError(t, err) certpool := x509.NewCertPool() - if !certpool.AppendCertsFromPEM(cafile) { - t.Errorf("the ca file isn't valid") - return - } + require.Truef(t, certpool.AppendCertsFromPEM(cafile), "the ca file isn't valid") tlsconfig := &tls.Config{RootCAs: certpool, ServerName: "testcontainer.go.test"} dockerReq := testcontainers.ContainerRequest{ @@ -299,10 +296,7 @@ func TestHTTPStrategyWaitUntilReadyWithQueryString(t *testing.T) { require.NoError(t, err) certpool := x509.NewCertPool() - if !certpool.AppendCertsFromPEM(cafile) { - t.Errorf("the ca file isn't valid") - return - } + require.Truef(t, certpool.AppendCertsFromPEM(cafile), "the ca file isn't valid") tlsconfig := &tls.Config{RootCAs: certpool, ServerName: "testcontainer.go.test"} dockerReq := testcontainers.ContainerRequest{ @@ -362,10 +356,7 @@ func TestHTTPStrategyWaitUntilReadyNoBasicAuth(t *testing.T) { require.NoError(t, err) certpool := x509.NewCertPool() - if !certpool.AppendCertsFromPEM(cafile) { - t.Errorf("the ca file isn't valid") - return - } + require.Truef(t, certpool.AppendCertsFromPEM(cafile), "the ca file isn't valid") // waitForHTTPStatusCode { tlsconfig := &tls.Config{RootCAs: certpool, ServerName: "testcontainer.go.test"}