From 80e57e194b1bd9341198b485ece84e73116c4ee4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20de=20la=20Pe=C3=B1a?= Date: Fri, 5 Jul 2024 18:50:39 +0200 Subject: [PATCH] feat: honour go toolchain's verbose flag to print out logs (#2624) * 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 --- Makefile | 2 +- docker_client.go | 3 +++ generic_test.go | 42 +++++++++++++++++++++++---------------- internal/config/config.go | 9 --------- logger.go | 33 ++++++++++++++++++++++++++++++ 5 files changed, 62 insertions(+), 27 deletions(-) diff --git a/Makefile b/Makefile index 33efe9e987..7c8c5e36b3 100644 --- a/Makefile +++ b/Makefile @@ -14,7 +14,7 @@ tidy-all: $(MAKE) -C examples tidy-examples $(MAKE) -C modules tidy-modules -## ------------------------------------- +## -------------------------------------- TCENV=tcvenv PYTHONBIN=./$(TCENV)/bin diff --git a/docker_client.go b/docker_client.go index 53db29c48b..105b994e4f 100644 --- a/docker_client.go +++ b/docker_client.go @@ -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" ) @@ -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 @@ -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(), diff --git a/generic_test.go b/generic_test.go index c566e925c1..9116fd0f65 100644 --- a/generic_test.go +++ b/generic_test.go @@ -3,7 +3,6 @@ package testcontainers import ( "context" "errors" - "net/http" "os" "os/exec" "strings" @@ -11,6 +10,8 @@ import ( "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" @@ -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{ @@ -133,6 +136,7 @@ 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")) @@ -140,11 +144,29 @@ func TestGenericReusableContainerInSubprocess(t *testing.T) { } 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)) @@ -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) } diff --git a/internal/config/config.go b/internal/config/config.go index cfdd8f30f6..9c96460414 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -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 diff --git a/logger.go b/logger.go index 4f77ce7b53..cfc851ad7e 100644 --- a/logger.go +++ b/logger.go @@ -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) @@ -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) {