Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions cmd/testDryRun.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,12 @@ func configureDriver(driver string) error {
case "podman":
return setupPodman()
case "docker":
return nil // testcontainers-go's default, via DOCKER_HOST
return connectors.ConfigureDockerHost() // ensure DOCKER_HOST is set before testcontainers-go connects
case "":
if shouldUsePodman() {
return setupPodman()
}
return nil
return connectors.ConfigureDockerHost()
default:
return errors.Wrapf(errors.KindUsage, "unsupported --driver %q (use 'docker' or 'podman')", driver)
}
Expand Down
47 changes: 47 additions & 0 deletions pkg/connectors/container_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import (
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
Expand Down Expand Up @@ -74,7 +75,50 @@ func NewContainerClient(driver string) (ContainerClient, error) {
}
}

var (
currentGOOS = runtime.GOOS
execCommandContext = exec.CommandContext
defaultSocketPath = "/var/run/docker.sock"
)
Comment on lines +78 to +82

@Harsh4902 Harsh4902 Sep 30, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need these extra variables?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They were added as test hooks so container_client_test.go can mock exec.Command and test the macOS context inspection and socket fallback scenarios on Linux CI runners (without needing a live Docker daemon).

If you'd prefer to keep container_client.go free of package-level test variables and keep the tests simpler, happy to remove them , let me know what u think.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry I lost track here. Why can't we just use function level variables then?

@ish-g09 ish-g09 Oct 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @Harsh4902, no worries!

The only reason they are package-level vars is so container_client_test.go can override them during tests.

Because GitHub Actions CI runs on Linux (runtime.GOOS == "linux"), having them as package-level variables allows the unit test to temporarily set currentGOOS = "darwin" and stub execCommand to test the macOS context inspection logic on Linux runners without needing a real Docker daemon. If they were function-level variables, the tests wouldn't be able to access or override them.

If you'd prefer to keep container_client.go free of package-level test variables, I can either, Move them into an internal helper like configureDockerHost(goos string, socketPath string, execCmd ...), or
Just inline runtime.GOOS, exec.Command, and "/var/run/docker.sock" directly in the function and simplify the test.
Let me know which approach you'd prefer!


// TODO: replace with docker/go-sdk context support
// ConfigureDockerHost ensures DOCKER_HOST points to an active Docker daemon socket.
// On macOS, Docker Desktop may not install the privileged /var/run/docker.sock symlink.
// If DOCKER_HOST is not explicitly set, we look for the user socket or inspect the active context.
func ConfigureDockerHost() error {
Comment thread
Harsh4902 marked this conversation as resolved.
Resolved
if os.Getenv("DOCKER_HOST") != "" || currentGOOS != "darwin" {
return nil
}

if _, err := os.Stat(defaultSocketPath); err == nil {
return nil
}

// Query the endpoint from the active docker context first to honor user configuration.
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()

out, err := execCommandContext(ctx, "docker", "context", "inspect", "--format", "{{.Endpoints.docker.Host}}").Output()
if err == nil {
if endpoint := strings.TrimSpace(string(out)); strings.HasPrefix(endpoint, "unix://") {
return os.Setenv("DOCKER_HOST", endpoint)
}
}

// Fall back to the standard Docker Desktop socket path on macOS.
if homeDir, err := os.UserHomeDir(); err == nil {
userSocket := filepath.Join(homeDir, ".docker", "run", "docker.sock")
if _, err := os.Stat(userSocket); err == nil {
return os.Setenv("DOCKER_HOST", "unix://"+userSocket)
}
}

return nil
}
func NewDockerClient() (*containerClient, error) {
if err := ConfigureDockerHost(); err != nil {
Comment thread
Harsh4902 marked this conversation as resolved.
Resolved
return nil, err
}
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())

if err != nil {
Expand All @@ -89,6 +133,9 @@ func NewDockerClient() (*containerClient, error) {
// an unreachable endpoint (e.g. a stopped Podman machine) before testcontainers-go
// silently resolves to a different runtime.
func PingDockerHost() error {
if err := ConfigureDockerHost(); err != nil {
return err
}
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return err
Expand Down
210 changes: 210 additions & 0 deletions pkg/connectors/container_client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
/*
* Copyright The Microcks Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package connectors

import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

// TestHelperProcess intercepts execCommand calls during unit tests.
func TestHelperProcess(t *testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
return
}
defer os.Exit(0)

args := os.Args
for len(args) > 0 {
if args[0] == "--" {
args = args[1:]
break
}
args = args[1:]
}
if len(args) == 0 {
fmt.Fprintln(os.Stderr, "no command provided")
os.Exit(2)
}

cmd, cmdArgs := args[0], args[1:]
switch cmd {
case "docker":
if os.Getenv("HELPER_DOCKER_FAIL") == "1" {
os.Exit(1)
}
if len(cmdArgs) >= 4 && cmdArgs[0] == "context" && cmdArgs[1] == "inspect" {
if custom := os.Getenv("HELPER_DOCKER_ENDPOINT"); custom != "" {
fmt.Println(custom)
} else {
fmt.Print("unix:///mock/active/docker.sock\n")
}
}
default:
os.Exit(2)
}
}

func mockExecCommandContext(envVars ...string) func(context.Context, string, ...string) *exec.Cmd {
return func(ctx context.Context, name string, args ...string) *exec.Cmd {
cs := []string{"-test.run=TestHelperProcess", "--", name}
cs = append(cs, args...)
cmd := exec.CommandContext(ctx, os.Args[0], cs...)
cmd.Env = append(os.Environ(), "GO_WANT_HELPER_PROCESS=1")
cmd.Env = append(cmd.Env, envVars...)
return cmd
}
}

func TestConfigureDockerHost_PreservesExistingDockerHost(t *testing.T) {
t.Setenv("DOCKER_HOST", "unix:///existing/custom.sock")

err := ConfigureDockerHost()
require.NoError(t, err)
assert.Equal(t, "unix:///existing/custom.sock", os.Getenv("DOCKER_HOST"))
}

func TestConfigureDockerHost_NonDarwin(t *testing.T) {
t.Setenv("DOCKER_HOST", "")
origGOOS := currentGOOS
currentGOOS = "linux"
defer func() { currentGOOS = origGOOS }()

err := ConfigureDockerHost()
require.NoError(t, err)
assert.Empty(t, os.Getenv("DOCKER_HOST"))
}

func TestConfigureDockerHost_DefaultSocketExists(t *testing.T) {
t.Setenv("DOCKER_HOST", "")
origGOOS := currentGOOS
origDefaultPath := defaultSocketPath
currentGOOS = "darwin"
tmpDir := t.TempDir()
dummySock := filepath.Join(tmpDir, "docker.sock")
require.NoError(t, os.WriteFile(dummySock, []byte(""), 0o600))
defaultSocketPath = dummySock
defer func() {
currentGOOS = origGOOS
defaultSocketPath = origDefaultPath
}()

err := ConfigureDockerHost()
require.NoError(t, err)
assert.Empty(t, os.Getenv("DOCKER_HOST"))
}

func TestConfigureDockerHost_InspectContextSuccess(t *testing.T) {
t.Setenv("DOCKER_HOST", "")
origGOOS := currentGOOS
origDefaultPath := defaultSocketPath
origExec := execCommandContext
currentGOOS = "darwin"
defaultSocketPath = filepath.Join(t.TempDir(), "nonexistent.sock")
execCommandContext = mockExecCommandContext()
defer func() {
currentGOOS = origGOOS
defaultSocketPath = origDefaultPath
execCommandContext = origExec
}()

err := ConfigureDockerHost()
require.NoError(t, err)
assert.Equal(t, "unix:///mock/active/docker.sock", os.Getenv("DOCKER_HOST"))
}

func TestConfigureDockerHost_InspectContextNonUnixEndpoint(t *testing.T) {
t.Setenv("DOCKER_HOST", "")
origGOOS := currentGOOS
origDefaultPath := defaultSocketPath
origExec := execCommandContext
currentGOOS = "darwin"
defaultSocketPath = filepath.Join(t.TempDir(), "nonexistent.sock")
execCommandContext = mockExecCommandContext("HELPER_DOCKER_ENDPOINT=tcp://192.168.1.100:2376")

tempHome := t.TempDir()
userSockDir := filepath.Join(tempHome, ".docker", "run")
require.NoError(t, os.MkdirAll(userSockDir, 0o755))
userSockFile := filepath.Join(userSockDir, "docker.sock")
require.NoError(t, os.WriteFile(userSockFile, []byte(""), 0o600))
t.Setenv("HOME", tempHome)

defer func() {
currentGOOS = origGOOS
defaultSocketPath = origDefaultPath
execCommandContext = origExec
}()

err := ConfigureDockerHost()
require.NoError(t, err)
assert.Equal(t, "unix://"+userSockFile, os.Getenv("DOCKER_HOST"))
}

func TestConfigureDockerHost_FallbackToUserSocket(t *testing.T) {
t.Setenv("DOCKER_HOST", "")
origGOOS := currentGOOS
origDefaultPath := defaultSocketPath
origExec := execCommandContext
currentGOOS = "darwin"
defaultSocketPath = filepath.Join(t.TempDir(), "nonexistent.sock")
execCommandContext = mockExecCommandContext("HELPER_DOCKER_FAIL=1")

tempHome := t.TempDir()
userSockDir := filepath.Join(tempHome, ".docker", "run")
require.NoError(t, os.MkdirAll(userSockDir, 0o755))
userSockFile := filepath.Join(userSockDir, "docker.sock")
require.NoError(t, os.WriteFile(userSockFile, []byte(""), 0o600))
t.Setenv("HOME", tempHome)

defer func() {
currentGOOS = origGOOS
defaultSocketPath = origDefaultPath
execCommandContext = origExec
}()

err := ConfigureDockerHost()
require.NoError(t, err)
assert.Equal(t, "unix://"+userSockFile, os.Getenv("DOCKER_HOST"))
}

func TestConfigureDockerHost_NeitherContextNorUserSocketAvailable(t *testing.T) {
t.Setenv("DOCKER_HOST", "")
origGOOS := currentGOOS
origDefaultPath := defaultSocketPath
origExec := execCommandContext
currentGOOS = "darwin"
defaultSocketPath = filepath.Join(t.TempDir(), "nonexistent.sock")
execCommandContext = mockExecCommandContext("HELPER_DOCKER_FAIL=1")
t.Setenv("HOME", t.TempDir())

defer func() {
currentGOOS = origGOOS
defaultSocketPath = origDefaultPath
execCommandContext = origExec
}()

err := ConfigureDockerHost()
require.NoError(t, err)
assert.Empty(t, os.Getenv("DOCKER_HOST"))
}
Loading