From 0d9e934ec7f62a1e164f7ce4f7560fa5c6b97d2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Duarte?= Date: Tue, 27 Aug 2024 14:02:59 +0100 Subject: [PATCH] Fix trailing slash on Image Prefix (#2747) * Fix trailing slash on Image Prefix * Apply Lint fix --- docker_test.go | 27 +++++++++++++++++++++++++++ options.go | 15 +++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/docker_test.go b/docker_test.go index f532d8650f..402d944dce 100644 --- a/docker_test.go +++ b/docker_test.go @@ -2280,3 +2280,30 @@ func TestDockerProvider_attemptToPullImage_retries(t *testing.T) { }) } } + +func TestCustomPrefixTrailingSlashIsProperlyRemovedIfPresent(t *testing.T) { + hubPrefixWithTrailingSlash := "public.ecr.aws/" + dockerImage := "amazonlinux/amazonlinux:2023" + + ctx := context.Background() + req := ContainerRequest{ + Image: dockerImage, + ImageSubstitutors: []ImageSubstitutor{newPrependHubRegistry(hubPrefixWithTrailingSlash)}, + } + + c, err := GenericContainer(ctx, GenericContainerRequest{ + ContainerRequest: req, + Started: true, + }) + if err != nil { + t.Fatal(err) + } + defer func() { + terminateContainerOnEnd(t, ctx, c) + }() + + // enforce the concrete type, as GenericContainer returns an interface, + // which will be changed in future implementations of the library + dockerContainer := c.(*DockerContainer) + assert.Equal(t, fmt.Sprintf("%s%s", hubPrefixWithTrailingSlash, dockerImage), dockerContainer.Image) +} diff --git a/options.go b/options.go index 6b5dcb1293..2849b15667 100644 --- a/options.go +++ b/options.go @@ -3,6 +3,7 @@ package testcontainers import ( "context" "fmt" + "net/url" "time" "dario.cat/mergo" @@ -155,7 +156,12 @@ func (c CustomHubSubstitutor) Substitute(image string) (string, error) { } } - return fmt.Sprintf("%s/%s", c.hub, image), nil + result, err := url.JoinPath(c.hub, image) + if err != nil { + return "", err + } + + return result, nil } // prependHubRegistry represents a way to prepend a custom Hub registry to the image name, @@ -198,7 +204,12 @@ func (p prependHubRegistry) Substitute(image string) (string, error) { } } - return fmt.Sprintf("%s/%s", p.prefix, image), nil + result, err := url.JoinPath(p.prefix, image) + if err != nil { + return "", err + } + + return result, nil } // WithImageSubstitutors sets the image substitutors for a container