Skip to content

Commit

Permalink
chore: use testify instead of t.Error (#2871)
Browse files Browse the repository at this point in the history
Switch to using testify require instead of manual comparisons and
t.Error to simplify and make tests more consistent.

Signed-off-by: Matthieu MOREL <[email protected]>
Co-authored-by: Steven Hartland <[email protected]>
  • Loading branch information
mmorel-35 and stevenh authored Nov 3, 2024
1 parent cc5a516 commit 19c1268
Show file tree
Hide file tree
Showing 12 changed files with 82 additions and 200 deletions.
20 changes: 7 additions & 13 deletions container_file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
package testcontainers

import (
"errors"
"os"
"path/filepath"
"testing"
Expand All @@ -14,7 +13,7 @@ import (
func TestContainerFileValidation(t *testing.T) {
type ContainerFileValidationTestCase struct {
Name string
ExpectedError error
ExpectedError string
File ContainerFile
}

Expand All @@ -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,
Expand All @@ -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: "",
Expand All @@ -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)
}
})
}
Expand Down
30 changes: 11 additions & 19 deletions container_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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: ".",
Expand All @@ -39,24 +39,21 @@ 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: ".",
},
},
},
{
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) {
Expand All @@ -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) {
Expand All @@ -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) {
Expand All @@ -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)
}
})
}
Expand Down
110 changes: 27 additions & 83 deletions docker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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) {
Expand Down Expand Up @@ -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) {
Expand All @@ -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.
Expand Down Expand Up @@ -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)
Expand All @@ -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) {
Expand All @@ -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) {
Expand Down Expand Up @@ -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")
Expand All @@ -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) {
Expand All @@ -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) {
Expand All @@ -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) {
Expand All @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
Loading

0 comments on commit 19c1268

Please sign in to comment.