Skip to content

Commit

Permalink
chore: add missing error handling and remove unused variables
Browse files Browse the repository at this point in the history
  • Loading branch information
hhsnopek committed Nov 8, 2022
1 parent 7dcdb92 commit 1624082
Show file tree
Hide file tree
Showing 21 changed files with 165 additions and 68 deletions.
6 changes: 5 additions & 1 deletion README.md
Expand Up @@ -68,7 +68,11 @@ func TestIntegrationNginxLatestReturn(t *testing.T) {
}

// Clean up the container after the test is complete
defer nginxC.Terminate(ctx)
defer func() {
if err := nginxC.terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %w", err)
}
}()

resp, err := http.Get(nginxC.URI)
if resp.StatusCode != http.StatusOK {
Expand Down
3 changes: 3 additions & 0 deletions compose_api.go
Expand Up @@ -25,8 +25,10 @@ func (f stackUpOptionFunc) applyToStackUp(o *stackUpOptions) {
f(o)
}

//nolint:unused
type stackDownOptionFunc func(do *api.DownOptions)

//nolint:unused
func (f stackDownOptionFunc) applyToStackDown(do *api.DownOptions) {
f(do)
}
Expand All @@ -42,6 +44,7 @@ func RunServices(serviceNames ...string) StackUpOption {
// IgnoreOrphans - Ignore legacy containers for services that are not defined in the project
type IgnoreOrphans bool

//nolint:unused
func (io IgnoreOrphans) applyToStackUp(co *api.CreateOptions, _ *api.StartOptions) {
co.IgnoreOrphans = bool(io)
}
Expand Down
8 changes: 3 additions & 5 deletions container_test.go
Expand Up @@ -324,7 +324,7 @@ func Test_BuildImageWithContexts(t *testing.T) {
} else if err != nil {
t.Fatal(err)
} else {
c.Terminate(ctx)
terminateContainerOnEnd(t, ctx, c)
}
})
}
Expand All @@ -346,7 +346,7 @@ func Test_GetLogsFromFailedContainer(t *testing.T) {
if err != nil && !errors.Is(err, context.DeadlineExceeded) {
t.Fatal(err)
} else if err == nil {
c.Terminate(ctx)
terminateContainerOnEnd(t, ctx, c)
t.Fatal("was expecting error starting container")
}

Expand Down Expand Up @@ -396,9 +396,7 @@ func createTestContainer(t *testing.T, ctx context.Context) int {
t.Fatalf("could not get mapped port: %v", err)
}

t.Cleanup(func() {
container.Terminate(context.Background())
})
terminateContainerOnEnd(t, ctx, container)

return port.Int()
}
Expand Down
8 changes: 2 additions & 6 deletions docker.go
Expand Up @@ -295,13 +295,9 @@ func (c *DockerContainer) Logs(ctx context.Context) (io.ReadCloser, error) {
r := bufio.NewReader(rc)

go func() {
var (
isPrefix = true
lineStarted = true
line []byte
)
var lineStarted = true
for err == nil {
line, isPrefix, err = r.ReadLine()
line, isPrefix, err := r.ReadLine()

if lineStarted && len(line) >= streamHeaderSize {
line = line[streamHeaderSize:] // trim stream header
Expand Down
54 changes: 39 additions & 15 deletions docker_test.go
Expand Up @@ -5,6 +5,7 @@ import (
"database/sql"
"errors"
"fmt"
"log"

// Import mysql into the scope of this package (required)
"io"
Expand Down Expand Up @@ -194,7 +195,7 @@ func TestContainerWithHostNetworkOptions_UseExposePortsFromImageConfigs(t *testi
t.Fatal(err)
}

defer nginxC.Terminate(ctx)
terminateContainerOnEnd(t, ctx, nginxC)

endpoint, err := nginxC.Endpoint(ctx, "http")
if err != nil {
Expand Down Expand Up @@ -225,7 +226,7 @@ func TestContainerWithNetworkModeAndNetworkTogether(t *testing.T) {
// Error when NetworkMode = host and Network = []string{"bridge"}
t.Logf("Can't use Network and NetworkMode together, %s", err)
}
defer nginx.Terminate(ctx)
terminateContainerOnEnd(t, ctx, nginx)
}

func TestContainerWithHostNetworkOptionsAndWaitStrategy(t *testing.T) {
Expand Down Expand Up @@ -636,9 +637,10 @@ func TestContainerTerminationRemovesDockerImage(t *testing.T) {
if err != nil {
t.Fatal(err)
}

_, _, err = client.ImageInspectWithRaw(ctx, imageID)
if err == nil {
t.Fatal("custom built image should have been removed")
t.Fatal("custom built image should have been removed", err)
}
})
}
Expand Down Expand Up @@ -686,6 +688,9 @@ func TestTwoContainersExposingTheSamePort(t *testing.T) {
}

endpointB, err := nginxB.PortEndpoint(ctx, nginxDefaultPort, "http")
if err != nil {
t.Fatal(err)
}

resp, err = http.Get(endpointB)
if err != nil {
Expand Down Expand Up @@ -1016,6 +1021,9 @@ func TestContainerCreationWaitsForLog(t *testing.T) {
"root", "password", host, port, "database")

db, err := sql.Open("mysql", connectionString)
if err != nil {
t.Fatal(err)
}
defer db.Close()

if err = db.Ping(); err != nil {
Expand Down Expand Up @@ -1719,7 +1727,11 @@ func ExampleDockerProvider_CreateContainer() {
ContainerRequest: req,
Started: true,
})
defer nginxC.Terminate(ctx)
defer func() {
if err := nginxC.Terminate(ctx); err != nil {
log.Fatalf("failed to terminate container: %s", err)
}
}()
}

func ExampleContainer_Host() {
Expand All @@ -1733,7 +1745,11 @@ func ExampleContainer_Host() {
ContainerRequest: req,
Started: true,
})
defer nginxC.Terminate(ctx)
defer func() {
if err := nginxC.Terminate(ctx); err != nil {
log.Fatalf("failed to terminate container: %s", err)
}
}()
ip, _ := nginxC.Host(ctx)
println(ip)
}
Expand All @@ -1748,7 +1764,11 @@ func ExampleContainer_Start() {
nginxC, _ := GenericContainer(ctx, GenericContainerRequest{
ContainerRequest: req,
})
defer nginxC.Terminate(ctx)
defer func() {
if err := nginxC.Terminate(ctx); err != nil {
log.Fatalf("failed to terminate container: %s", err)
}
}()
_ = nginxC.Start(ctx)
}

Expand All @@ -1762,7 +1782,11 @@ func ExampleContainer_Stop() {
nginxC, _ := GenericContainer(ctx, GenericContainerRequest{
ContainerRequest: req,
})
defer nginxC.Terminate(ctx)
defer func() {
if err := nginxC.Terminate(ctx); err != nil {
log.Fatalf("failed to terminate container: %s", err)
}
}()
timeout := 10 * time.Second
_ = nginxC.Stop(ctx, &timeout)
}
Expand All @@ -1778,7 +1802,11 @@ func ExampleContainer_MappedPort() {
ContainerRequest: req,
Started: true,
})
defer nginxC.Terminate(ctx)
defer func() {
if err := nginxC.Terminate(ctx); err != nil {
log.Fatalf("failed to terminate container: %s", err)
}
}()
ip, _ := nginxC.Host(ctx)
port, _ := nginxC.MappedPort(ctx, "80")
_, _ = http.Get(fmt.Sprintf("http://%s:%s", ip, port.Port()))
Expand Down Expand Up @@ -1826,7 +1854,7 @@ func TestContainerCreationWithBindAndVolume(t *testing.T) {
})

require.NoError(t, err)
require.NoError(t, bashC.Terminate(ctx))
terminateContainerOnEnd(t, ctx, bashC)
}

func TestContainerWithTmpFs(t *testing.T) {
Expand Down Expand Up @@ -1926,11 +1954,7 @@ func TestContainerCustomPlatformImage(t *testing.T) {
Started: false,
})

t.Cleanup(func() {
if c != nil {
c.Terminate(ctx)
}
})
terminateContainerOnEnd(t, ctx, c)

assert.Error(t, err)
})
Expand Down Expand Up @@ -2450,7 +2474,7 @@ func TestContainerRunningCheckingStatusCode(t *testing.T) {
t.Fatal(err)
}

defer influx.Terminate(ctx)
terminateContainerOnEnd(t, ctx, influx)
}

func TestContainerWithUserID(t *testing.T) {
Expand Down
6 changes: 5 additions & 1 deletion docs/examples/cockroachdb.md
Expand Up @@ -94,7 +94,11 @@ func TestIntegrationDBInsertSelect(t *testing.T) {
if err != nil {
t.Fatal(err)
}
defer cdbContainer.Terminate(ctx)
t.Cleanup(func() {
if err := cdbContainer.Terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %s", err)
}
})

db, err := sql.Open("pgx", cdbContainer.URI+"/projectmanagement")
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/nginx.md
Expand Up @@ -60,7 +60,7 @@ func TestIntegrationNginxLatestReturn(t *testing.T) {
}

// Clean up the container after the test is complete
defer nginxC.Terminate(ctx)
testcontainers.Cleanup(t, ctx, nginxC)

resp, err := http.Get(nginxC.URI)
if resp.StatusCode != http.StatusOK {
Expand Down
14 changes: 11 additions & 3 deletions docs/features/creating_container.md
Expand Up @@ -74,7 +74,11 @@ func TestIntegrationNginxLatestReturn(t *testing.T) {
}

// Clean up the container after the test is complete
defer nginxC.Terminate(ctx)
t.Cleanup(func() {
if err := nginxC.Terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %s", err)
}
})

resp, err := http.Get(nginxC.URI)
if resp.StatusCode != http.StatusOK {
Expand Down Expand Up @@ -193,7 +197,6 @@ func main() {
}

res, err := testcontainers.ParallelContainers(ctx, requests, testcontainers.ParallelContainersOptions{})

if err != nil {
e, ok := err.(testcontainers.ParallelContainersError)
if !ok {
Expand All @@ -207,7 +210,12 @@ func main() {
}

for _, c := range res {
defer c.Terminate(ctx)
c := c
defer func() {
if err := c.Terminate(ctx); err != nil {
log.Fatalf("failed to terminate container: %s", c)
}
}()
}
}
```
9 changes: 7 additions & 2 deletions docs/quickstart/gotest.md
Expand Up @@ -35,7 +35,11 @@ func TestWithRedis(t *testing.T) {
if err != nil {
t.Error(err)
}
defer redisC.Terminate(ctx)
defer func() {
if err := redisC.terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %w", err)
}
}()
}
```

Expand Down Expand Up @@ -66,7 +70,8 @@ start, leaving to you the decision about when to start it.

All the containers must be removed at some point, otherwise they will run until
the host is overloaded. One of the ways we have to clean up is by deferring the
terminated function: `defer redisC.Terminate(ctx)`.
terminated function: `defer redisC.Terminate(ctx)`. Optionally you may use
terminate a container with the helper `tescontainers.CleaupContainer(t, ctx, redisC)`.

!!!tip

Expand Down
18 changes: 15 additions & 3 deletions e2e/container_test.go
Expand Up @@ -7,6 +7,7 @@ import (
"time"

"github.com/docker/go-connections/nat"
"github.com/stretchr/testify/require"
. "github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"

Expand Down Expand Up @@ -45,7 +46,7 @@ func TestContainerWithWaitForSQL(t *testing.T) {
t.Fatal(err)
}

defer container.Terminate(ctx)
terminateContainerOnEnd(t, ctx, container)
})
t.Run("custom query", func(t *testing.T) {
req := ContainerRequest{
Expand All @@ -65,7 +66,7 @@ func TestContainerWithWaitForSQL(t *testing.T) {
t.Fatal(err)
}

defer container.Terminate(ctx)
terminateContainerOnEnd(t, ctx, container)
})
t.Run("custom bad query", func(t *testing.T) {
req := ContainerRequest{
Expand All @@ -85,6 +86,17 @@ func TestContainerWithWaitForSQL(t *testing.T) {
t.Fatal("expected error, but got a nil")
}

defer container.Terminate(ctx)
terminateContainerOnEnd(t, ctx, container)
})
}

func terminateContainerOnEnd(tb testing.TB, ctx context.Context, ctr Container) {
tb.Helper()
if ctr == nil {
return
}
tb.Cleanup(func() {
tb.Log("terminating container")
require.NoError(tb, ctr.Terminate(ctx))
})
}
5 changes: 4 additions & 1 deletion file.go
Expand Up @@ -40,7 +40,7 @@ func tarDir(src string, fileMode int64) (*bytes.Buffer, error) {
tw := tar.NewWriter(zr)

// walk through every file in the folder
filepath.Walk(src, func(file string, fi os.FileInfo, errFn error) error {
err := filepath.Walk(src, func(file string, fi os.FileInfo, errFn error) error {
if errFn != nil {
return fmt.Errorf("error traversing the file system: %w", errFn)
}
Expand Down Expand Up @@ -80,6 +80,9 @@ func tarDir(src string, fileMode int64) (*bytes.Buffer, error) {
}
return nil
})
if err != nil {
return buffer, err
}

// produce tar
if err := tw.Close(); err != nil {
Expand Down
1 change: 0 additions & 1 deletion generic_test.go
Expand Up @@ -29,7 +29,6 @@ func TestGenericReusableContainer(t *testing.T) {
})
require.NoError(t, err)
require.True(t, n1.IsRunning())

terminateContainerOnEnd(t, ctx, n1)

copiedFileName := "hello_copy.sh"
Expand Down

0 comments on commit 1624082

Please sign in to comment.