Skip to content

Commit

Permalink
Add function to get docker resource by name (#172)
Browse files Browse the repository at this point in the history
  • Loading branch information
prochac authored and aeneasr committed Oct 31, 2019
1 parent c745b8f commit 11b6eae
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
28 changes: 28 additions & 0 deletions dockertest.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,34 @@ func (d *Pool) Run(repository, tag string, env []string) (*Resource, error) {
return d.RunWithOptions(&RunOptions{Repository: repository, Tag: tag, Env: env})
}

// ContainerByName finds a container with the given name and returns it if present
func (d *Pool) ContainerByName(containerName string) (*Resource, bool) {
containers, err := d.Client.ListContainers(dc.ListContainersOptions{
All: true,
Filters: map[string][]string{
"name": {containerName},
},
})

if err != nil {
return nil, false
}

if len(containers) == 0 {
return nil, false
}

c, err := d.Client.InspectContainer(containers[0].ID)
if err != nil {
return nil, false
}

return &Resource{
pool: d,
Container: c,
}, true
}

// RemoveContainerByName find a container with the given name and removes it if present
func (d *Pool) RemoveContainerByName(containerName string) error {
containers, err := d.Client.ListContainers(dc.ListContainersOptions{
Expand Down
17 changes: 17 additions & 0 deletions dockertest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,23 @@ func TestContainerWithShMzSize(t *testing.T) {
require.Nil(t, pool.Purge(resource))
}

func TestContainerByName(t *testing.T) {
got, err := pool.RunWithOptions(
&RunOptions{
Name: "db",
Repository: "postgres",
Tag: "9.5",
})
require.Nil(t, err)

want, ok := pool.ContainerByName("db")
require.True(t, ok)

require.Equal(t, got, want)

require.Nil(t, pool.Purge(got))
}

func TestRemoveContainerByName(t *testing.T) {
_, err := pool.RunWithOptions(
&RunOptions{
Expand Down

0 comments on commit 11b6eae

Please sign in to comment.