Skip to content

Commit 9b544b3

Browse files
dennwcarekkas
authored andcommitted
Adds GetHostPort and Close helpers to Resource (#126)
1 parent 2e92e77 commit 9b544b3

File tree

1 file changed

+30
-1
lines changed

1 file changed

+30
-1
lines changed

dockertest.go

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package dockertest
33
import (
44
"fmt"
55
"io/ioutil"
6+
"net"
67
"os"
78
"path/filepath"
89
"runtime"
@@ -22,6 +23,7 @@ type Pool struct {
2223

2324
// Resource represents a docker container.
2425
type Resource struct {
26+
pool *Pool
2527
Container *dc.Container
2628
}
2729

@@ -60,6 +62,32 @@ func (r *Resource) GetBoundIP(id string) string {
6062
return m[0].HostIP
6163
}
6264

65+
// GetHostPort returns a resource's published port with an address.
66+
func (r *Resource) GetHostPort(portID string) string {
67+
if r.Container == nil {
68+
return ""
69+
} else if r.Container.NetworkSettings == nil {
70+
return ""
71+
}
72+
73+
m, ok := r.Container.NetworkSettings.Ports[dc.Port(portID)]
74+
if !ok {
75+
return ""
76+
} else if len(m) == 0 {
77+
return ""
78+
}
79+
ip := m[0].HostIP
80+
if ip == "0.0.0.0" {
81+
ip = "localhost"
82+
}
83+
return net.JoinHostPort(ip, m[0].HostPort)
84+
}
85+
86+
// Close removes a container and linked volumes from docker by calling pool.Purge.
87+
func (r *Resource) Close() error {
88+
return r.pool.Purge(r)
89+
}
90+
6391
// NewTLSPool creates a new pool given an endpoint and the certificate path. This is required for endpoints that
6492
// require TLS communication.
6593
func NewTLSPool(endpoint, certpath string) (*Pool, error) {
@@ -221,7 +249,7 @@ func (d *Pool) RunWithOptions(opts *RunOptions) (*Resource, error) {
221249
Cmd: cmd,
222250
Mounts: mounts,
223251
ExposedPorts: exp,
224-
WorkingDir: wd,
252+
WorkingDir: wd,
225253
},
226254
HostConfig: &dc.HostConfig{
227255
PublishAllPorts: true,
@@ -245,6 +273,7 @@ func (d *Pool) RunWithOptions(opts *RunOptions) (*Resource, error) {
245273
}
246274

247275
return &Resource{
276+
pool: d,
248277
Container: c,
249278
}, nil
250279
}

0 commit comments

Comments
 (0)