Skip to content

Commit

Permalink
feat: honour go toolchain's verbose flag to print out logs (#2624)
Browse files Browse the repository at this point in the history
* chore: disable logging if the "-v" flag is not present

* chore: print ryuk is disabled using the logger

* fix: lint

* fix: force verbosity in subprocess test

* chore: include library version in banner

* fix: terminate reusable container in tests

* fix: remove container out-of-process in the right place

* chore: refresh github

* chore: simply check the reusable container is running without failures
  • Loading branch information
mdelapenya authored Jul 5, 2024
1 parent 306f185 commit 80e57e1
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 27 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ tidy-all:
$(MAKE) -C examples tidy-examples
$(MAKE) -C modules tidy-modules

## -------------------------------------
## --------------------------------------

TCENV=tcvenv
PYTHONBIN=./$(TCENV)/bin
Expand Down
3 changes: 3 additions & 0 deletions docker_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/docker/docker/api/types/system"
"github.com/docker/docker/client"

"github.com/testcontainers/testcontainers-go/internal"
"github.com/testcontainers/testcontainers-go/internal/core"
)

Expand Down Expand Up @@ -57,6 +58,7 @@ func (c *DockerClient) Info(ctx context.Context) (system.Info, error) {
API Version: %v
Operating System: %v
Total Memory: %v MB
Testcontainers for Go Version: v%s
Resolved Docker Host: %s
Resolved Docker Socket Path: %s
Test SessionID: %s
Expand All @@ -66,6 +68,7 @@ func (c *DockerClient) Info(ctx context.Context) (system.Info, error) {
Logger.Printf(infoMessage, packagePath,
dockerInfo.ServerVersion, c.Client.ClientVersion(),
dockerInfo.OperatingSystem, dockerInfo.MemTotal/1024/1024,
internal.Version,
core.ExtractDockerHost(ctx),
core.ExtractDockerSocket(ctx),
core.SessionID(),
Expand Down
42 changes: 25 additions & 17 deletions generic_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@ package testcontainers
import (
"context"
"errors"
"net/http"
"os"
"os/exec"
"strings"
"sync"
"testing"
"time"

"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/stretchr/testify/require"

"github.com/testcontainers/testcontainers-go/wait"
Expand All @@ -23,6 +24,8 @@ const (
func TestGenericReusableContainer(t *testing.T) {
ctx := context.Background()

reusableContainerName := reusableContainerName + "_" + time.Now().Format("20060102150405")

n1, err := GenericContainer(ctx, GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: ContainerRequest{
Expand Down Expand Up @@ -133,18 +136,37 @@ func TestGenericReusableContainerInSubprocess(t *testing.T) {
// create containers in subprocesses, as "go test ./..." does.
output := createReuseContainerInSubprocess(t)

t.Log(output)
// check is reuse container with WaitingFor work correctly.
require.True(t, strings.Contains(output, "⏳ Waiting for container id"))
require.True(t, strings.Contains(output, "🔔 Container is ready"))
}()
}

wg.Wait()

cli, err := NewDockerClientWithOpts(context.Background())
require.NoError(t, err)

f := filters.NewArgs(filters.KeyValuePair{Key: "name", Value: reusableContainerName})

ctrs, err := cli.ContainerList(context.Background(), container.ListOptions{
All: true,
Filters: f,
})
require.NoError(t, err)
require.Len(t, ctrs, 1)

nginxC, err := containerFromDockerResponse(context.Background(), ctrs[0])
require.NoError(t, err)

terminateContainerOnEnd(t, context.Background(), nginxC)
}

func createReuseContainerInSubprocess(t *testing.T) string {
cmd := exec.Command(os.Args[0], "-test.run=TestHelperContainerStarterProcess")
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
// force verbosity in subprocesses, so that the output is printed
cmd := exec.Command(os.Args[0], "-test.run=TestHelperContainerStarterProcess", "-test.v=true")
cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")

output, err := cmd.CombinedOutput()
require.NoError(t, err, string(output))
Expand Down Expand Up @@ -174,18 +196,4 @@ func TestHelperContainerStarterProcess(t *testing.T) {
})
require.NoError(t, err)
require.True(t, nginxC.IsRunning())

origin, err := nginxC.PortEndpoint(ctx, nginxDefaultPort, "http")
require.NoError(t, err)

// check is reuse container with WaitingFor work correctly.
req, err := http.NewRequestWithContext(ctx, http.MethodGet, origin, nil)
require.NoError(t, err)
req.Close = true

resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()

require.Equal(t, http.StatusOK, resp.StatusCode)
}
9 changes: 0 additions & 9 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,6 @@ type Config struct {
func Read() Config {
tcConfigOnce.Do(func() {
tcConfig = read()

if tcConfig.RyukDisabled {
ryukDisabledMessage := `
**********************************************************************************************
Ryuk has been disabled for the current execution. This can cause unexpected behavior in your environment.
More on this: https://golang.testcontainers.org/features/garbage_collector/
**********************************************************************************************`
fmt.Println(ryukDisabledMessage)
}
})

return tcConfig
Expand Down
33 changes: 33 additions & 0 deletions logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,40 @@ import (
"context"
"log"
"os"
"strings"
"testing"

"github.com/docker/docker/client"

"github.com/testcontainers/testcontainers-go/internal/config"
)

// Logger is the default log instance
var Logger Logging = log.New(os.Stderr, "", log.LstdFlags)

func init() {
verbose := false
for _, arg := range os.Args {
if strings.EqualFold(arg, "-test.v=true") || strings.EqualFold(arg, "-v") {
verbose = true
break
}
}

if !verbose {
Logger = &noopLogger{}
}

if config.Read().RyukDisabled {
ryukDisabledMessage := `
**********************************************************************************************
Ryuk has been disabled for the current execution. This can cause unexpected behavior in your environment.
More on this: https://golang.testcontainers.org/features/garbage_collector/
**********************************************************************************************`
Logger.Printf(ryukDisabledMessage)
}
}

// Validate our types implement the required interfaces.
var (
_ Logging = (*log.Logger)(nil)
Expand All @@ -25,6 +51,13 @@ type Logging interface {
Printf(format string, v ...interface{})
}

type noopLogger struct{}

// Printf implements Logging.
func (n noopLogger) Printf(format string, v ...interface{}) {
// NOOP
}

// Deprecated: this function will be removed in a future release
// LogDockerServerInfo logs the docker server info using the provided logger and Docker client
func LogDockerServerInfo(ctx context.Context, client client.APIClient, logger Logging) {
Expand Down

0 comments on commit 80e57e1

Please sign in to comment.