github.com/simonferquel/app@v0.6.1-0.20181012141724-68b7cccf26ac/e2e/helper.go (about) 1 package e2e 2 3 import ( 4 "fmt" 5 "strconv" 6 "strings" 7 "testing" 8 "time" 9 10 "gotest.tools/icmd" 11 ) 12 13 // Container represents a docker container 14 type Container struct { 15 image string 16 privatePort int 17 address string 18 container string 19 } 20 21 // NewContainer creates a new Container 22 func NewContainer(image string, privatePort int) *Container { 23 return &Container{ 24 image: image, 25 privatePort: privatePort, 26 } 27 } 28 29 // Start starts a new docker container on a random port 30 func (c *Container) Start(t *testing.T) { 31 result := icmd.RunCommand("docker", "run", "--rm", "-d", "-P", c.image).Assert(t, icmd.Success) 32 c.container = strings.Trim(result.Stdout(), " \r\n") 33 time.Sleep(time.Second * 3) 34 } 35 36 // Stop terminates this container 37 func (c *Container) Stop(t *testing.T) { 38 icmd.RunCommand("docker", "stop", c.container).Assert(t, icmd.Success) 39 } 40 41 // GetAddress returns the host:port this container listens on 42 func (c *Container) GetAddress(t *testing.T) string { 43 if c.address != "" { 44 return c.address 45 } 46 result := icmd.RunCommand("docker", "port", c.container, strconv.Itoa(c.privatePort)).Assert(t, icmd.Success) 47 c.address = fmt.Sprintf("127.0.0.1:%v", strings.Trim(strings.Split(result.Stdout(), ":")[1], " \r\n")) 48 return c.address 49 }