Skip to content

Commit

Permalink
fix: use regex to find container by name
Browse files Browse the repository at this point in the history
  • Loading branch information
hwwwi committed Oct 8, 2022
1 parent 38fbdc6 commit 62e95c4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
4 changes: 3 additions & 1 deletion docker.go
Expand Up @@ -1109,9 +1109,11 @@ func (p *DockerProvider) findContainerByName(ctx context.Context, name string) (
if name == "" {
return nil, nil
}

// Note that, 'name' filter will use regex to find the containers
filter := filters.NewArgs(filters.KeyValuePair{
Key: "name",
Value: name,
Value: fmt.Sprintf("^%s$", name),
})
containers, err := p.client.ContainerList(ctx, types.ContainerListOptions{Filters: filter})
if err != nil {
Expand Down
41 changes: 38 additions & 3 deletions docker_test.go
Expand Up @@ -5,6 +5,7 @@ import (
"database/sql"
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"io"
"io/ioutil"
"math/rand"
Expand All @@ -28,9 +29,6 @@ import (

"github.com/docker/docker/api/types/volume"

// Import mysql into the scope of this package (required)
_ "github.com/go-sql-driver/mysql"

"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
Expand Down Expand Up @@ -2398,3 +2396,40 @@ func randomString() string {
}
return b.String()
}

func TestDockerProviderFindContainerByName(t *testing.T) {
ctx := context.Background()
provider, err := NewDockerProvider(WithLogger(TestLogger(t)))
require.NoError(t, err)

c1, err := GenericContainer(ctx, GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: ContainerRequest{
Name: "test",
Image: "nginx:1.17.6",
WaitingFor: wait.ForExposedPort(),
},
Started: true,
})
require.NoError(t, err)
c1Name, err := c1.Name(ctx)
require.NoError(t, err)
terminateContainerOnEnd(t, ctx, c1)

c2, err := GenericContainer(ctx, GenericContainerRequest{
ProviderType: providerType,
ContainerRequest: ContainerRequest{
Name: "test2",
Image: "nginx:1.17.6",
WaitingFor: wait.ForExposedPort(),
},
Started: true,
})
require.NoError(t, err)
terminateContainerOnEnd(t, ctx, c2)

c, err := provider.findContainerByName(ctx, "test")
assert.NoError(t, err)
require.NotNil(t, c)
assert.Contains(t, c.Names, c1Name)
}

0 comments on commit 62e95c4

Please sign in to comment.