/* Copyright 2014 The Camlistore Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* Package dockertest contains helper functions for setting up and tearing down docker containers to aid in testing. */ package dockertest import ( "bytes" "encoding/json" "errors" "fmt" "os/exec" "strings" ) func HaveImage(name string) (ok bool, err error) { out, err := exec.Command("docker", "images", "--no-trunc").Output() if err != nil { return } return bytes.Contains(out, []byte(name)), nil } func Run(args ...string) (containerID string, err error) { runOut, err := exec.Command("docker", append([]string{"run"}, args...)...).Output() if err != nil { return } containerID = strings.TrimSpace(string(runOut)) if containerID == "" { return "", errors.New("unexpected empty output from `docker run`") } return } func KillContainer(container string) error { return exec.Command("docker", "kill", container).Run() } func Pull(name string) error { out, err := exec.Command("docker", "pull", name).CombinedOutput() if err != nil { err = fmt.Errorf("%v: %s", err, out) } return err } func IP(containerID string) (string, error) { out, err := exec.Command("docker", "inspect", containerID).Output() if err != nil { return "", err } type networkSettings struct { IPAddress string } type container struct { NetworkSettings networkSettings } var c []container if err := json.NewDecoder(bytes.NewReader(out)).Decode(&c); err != nil { return "", err } if len(c) == 0 { return "", errors.New("no output from docker inspect") } if ip := c[0].NetworkSettings.IPAddress; ip != "" { return ip, nil } return "", errors.New("no IP. Not running?") }