本文整理匯總了Golang中github.com/docker/docker/pkg/testutil/cmd.RunCommand函數的典型用法代碼示例。如果您正苦於以下問題:Golang RunCommand函數的具體用法?Golang RunCommand怎麽用?Golang RunCommand使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了RunCommand函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestHelpExitCodesHelpOutput
func (s *DockerSuite) TestHelpExitCodesHelpOutput(c *check.C) {
// Test to make sure the exit code and output (stdout vs stderr) of
// various good and bad cases are what we expect
// docker : stdout=all, stderr=empty, rc=0
out, _ := dockerCmd(c)
// Be really pick
c.Assert(out, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have a blank line at the end of 'docker'\n"))
// docker help: stdout=all, stderr=empty, rc=0
out, _ = dockerCmd(c, "help")
// Be really pick
c.Assert(out, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have a blank line at the end of 'docker help'\n"))
// docker --help: stdout=all, stderr=empty, rc=0
out, _ = dockerCmd(c, "--help")
// Be really pick
c.Assert(out, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have a blank line at the end of 'docker --help'\n"))
// docker inspect busybox: stdout=all, stderr=empty, rc=0
// Just making sure stderr is empty on valid cmd
out, _ = dockerCmd(c, "inspect", "busybox")
// Be really pick
c.Assert(out, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have a blank line at the end of 'docker inspect busyBox'\n"))
// docker rm: stdout=empty, stderr=all, rc!=0
// testing the min arg error msg
icmd.RunCommand(dockerBinary, "rm").Assert(c, icmd.Expected{
ExitCode: 1,
Error: "exit status 1",
Out: "",
// Should not contain full help text but should contain info about
// # of args and Usage line
Err: "requires at least 1 argument",
})
// docker rm NoSuchContainer: stdout=empty, stderr=all, rc=0
// testing to make sure no blank line on error
result := icmd.RunCommand(dockerBinary, "rm", "NoSuchContainer")
result.Assert(c, icmd.Expected{
ExitCode: 1,
Error: "exit status 1",
Out: "",
})
// Be really picky
c.Assert(len(result.Stderr()), checker.Not(checker.Equals), 0)
c.Assert(result.Stderr(), checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have a blank line at the end of 'docker rm'\n"))
// docker BadCmd: stdout=empty, stderr=all, rc=0
icmd.RunCommand(dockerBinary, "BadCmd").Assert(c, icmd.Expected{
ExitCode: 1,
Error: "exit status 1",
Out: "",
Err: "docker: 'BadCmd' is not a docker command.\nSee 'docker --help'\n",
})
}
示例2: RunAtDifferentDate
// RunAtDifferentDate runs the specified function with the given time.
// It changes the date of the system, which can led to weird behaviors.
func RunAtDifferentDate(date time.Time, block func()) {
// Layout for date. MMDDhhmmYYYY
const timeLayout = "010203042006"
// Ensure we bring time back to now
now := time.Now().Format(timeLayout)
defer icmd.RunCommand("date", now)
icmd.RunCommand("date", date.Format(timeLayout))
block()
return
}
示例3: TestLogsSince
func (s *DockerSuite) TestLogsSince(c *check.C) {
name := "testlogssince"
dockerCmd(c, "run", "--name="+name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do sleep 2; echo log$i; done")
out, _ := dockerCmd(c, "logs", "-t", name)
log2Line := strings.Split(strings.Split(out, "\n")[1], " ")
t, err := time.Parse(time.RFC3339Nano, log2Line[0]) // the timestamp log2 is written
c.Assert(err, checker.IsNil)
since := t.Unix() + 1 // add 1s so log1 & log2 doesn't show up
out, _ = dockerCmd(c, "logs", "-t", fmt.Sprintf("--since=%v", since), name)
// Skip 2 seconds
unexpected := []string{"log1", "log2"}
for _, v := range unexpected {
c.Assert(out, checker.Not(checker.Contains), v, check.Commentf("unexpected log message returned, since=%v", since))
}
// Test to make sure a bad since format is caught by the client
out, _, _ = dockerCmdWithError("logs", "-t", "--since=2006-01-02T15:04:0Z", name)
c.Assert(out, checker.Contains, "cannot parse \"0Z\" as \"05\"", check.Commentf("bad since format passed to server"))
// Test with default value specified and parameter omitted
expected := []string{"log1", "log2", "log3"}
for _, cmd := range [][]string{
{"logs", "-t", name},
{"logs", "-t", "--since=0", name},
} {
result := icmd.RunCommand(dockerBinary, cmd...)
result.Assert(c, icmd.Success)
for _, v := range expected {
c.Assert(result.Combined(), checker.Contains, v)
}
}
}
示例4: WaitInspectWithArgs
// WaitInspectWithArgs waits for the specified expression to be equals to the specified expected string in the given time.
// FIXME(vdemeester) Attach this to the Daemon struct
func WaitInspectWithArgs(dockerBinary, name, expr, expected string, timeout time.Duration, arg ...string) error {
after := time.After(timeout)
args := append(arg, "inspect", "-f", expr, name)
for {
result := icmd.RunCommand(dockerBinary, args...)
if result.Error != nil {
if !strings.Contains(result.Stderr(), "No such") {
return errors.Errorf("error executing docker inspect: %v\n%s",
result.Stderr(), result.Stdout())
}
select {
case <-after:
return result.Error
default:
time.Sleep(10 * time.Millisecond)
continue
}
}
out := strings.TrimSpace(result.Stdout())
if out == expected {
break
}
select {
case <-after:
return errors.Errorf("condition \"%q == %q\" not true in time (%v)", out, expected, timeout)
default:
}
time.Sleep(100 * time.Millisecond)
}
return nil
}
示例5: TestWaitBlockedExitZero
// blocking wait with 0 exit code
func (s *DockerSuite) TestWaitBlockedExitZero(c *check.C) {
// Windows busybox does not support trap in this way, not sleep with sub-second
// granularity. It will always exit 0x40010004.
testRequires(c, DaemonIsLinux)
out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "trap 'exit 0' TERM; while true; do usleep 10; done")
containerID := strings.TrimSpace(out)
c.Assert(waitRun(containerID), checker.IsNil)
chWait := make(chan string)
go func() {
chWait <- ""
out := icmd.RunCommand(dockerBinary, "wait", containerID).Combined()
chWait <- out
}()
<-chWait // make sure the goroutine is started
time.Sleep(100 * time.Millisecond)
dockerCmd(c, "stop", containerID)
select {
case status := <-chWait:
c.Assert(strings.TrimSpace(status), checker.Equals, "0", check.Commentf("expected exit 0, got %s", status))
case <-time.After(2 * time.Second):
c.Fatal("timeout waiting for `docker wait` to exit")
}
}
示例6: dockerCmd
func dockerCmd(c *check.C, args ...string) (string, int) {
if err := validateArgs(args...); err != nil {
c.Fatalf(err.Error())
}
result := icmd.RunCommand(dockerBinary, args...)
c.Assert(result, icmd.Matches, icmd.Success)
return result.Combined(), result.ExitCode
}
示例7: inspectFilter
func inspectFilter(name, filter string) (string, error) {
format := fmt.Sprintf("{{%s}}", filter)
result := icmd.RunCommand(dockerBinary, "inspect", "-f", format, name)
if result.Error != nil || result.ExitCode != 0 {
return "", fmt.Errorf("failed to inspect %s: %s", name, result.Combined())
}
return strings.TrimSpace(result.Combined()), nil
}
示例8: dockerCmdWithError
func dockerCmdWithError(args ...string) (string, int, error) {
if err := validateArgs(args...); err != nil {
return "", 0, err
}
result := icmd.RunCommand(dockerBinary, args...)
if result.Error != nil {
return result.Combined(), result.ExitCode, result.Compare(icmd.Success)
}
return result.Combined(), result.ExitCode, result.Error
}
示例9: deleteContainer
// FIXME(vdemeester) move this away are remove ignoreNoSuchContainer bool
func deleteContainer(ignoreNoSuchContainer bool, container ...string) error {
result := icmd.RunCommand(dockerBinary, append([]string{"rm", "-fv"}, container...)...)
if ignoreNoSuchContainer && result.Error != nil {
// If the error is "No such container: ..." this means the container doesn't exists anymore,
// we can safely ignore that one.
if strings.Contains(result.Error.Error(), "No such container") {
return nil
}
}
return result.Compare(icmd.Success)
}
示例10: TestExecParseError
// FIXME(vdemeester) this should be a unit tests on cli/command/container package
func (s *DockerSuite) TestExecParseError(c *check.C) {
// TODO Windows CI: Requires some extra work. Consider copying the
// runSleepingContainer helper to have an exec version.
testRequires(c, DaemonIsLinux)
dockerCmd(c, "run", "-d", "--name", "top", "busybox", "top")
// Test normal (non-detached) case first
icmd.RunCommand(dockerBinary, "exec", "top").Assert(c, icmd.Expected{
ExitCode: 1,
Error: "exit status 1",
Err: "See 'docker exec --help'",
})
}
示例11: TestVolumeCLINoArgs
// FIXME(vdemeester) should be a unit test in cli/command/volume package
func (s *DockerSuite) TestVolumeCLINoArgs(c *check.C) {
out, _ := dockerCmd(c, "volume")
// no args should produce the cmd usage output
usage := "Usage: docker volume COMMAND"
c.Assert(out, checker.Contains, usage)
// invalid arg should error and show the command usage on stderr
icmd.RunCommand(dockerBinary, "volume", "somearg").Assert(c, icmd.Expected{
ExitCode: 1,
Error: "exit status 1",
Err: usage,
})
// invalid flag should error and show the flag error and cmd usage
result := icmd.RunCommand(dockerBinary, "volume", "--no-such-flag")
result.Assert(c, icmd.Expected{
ExitCode: 125,
Error: "exit status 125",
Err: usage,
})
c.Assert(result.Stderr(), checker.Contains, "unknown flag: --no-such-flag")
}
示例12: TestConfigHTTPHeader
func (s *DockerSuite) TestConfigHTTPHeader(c *check.C) {
testRequires(c, UnixCli) // Can't set/unset HOME on windows right now
// We either need a level of Go that supports Unsetenv (for cases
// when HOME/USERPROFILE isn't set), or we need to be able to use
// os/user but user.Current() only works if we aren't statically compiling
var headers map[string][]string
server := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("API-Version", api.DefaultVersion)
headers = r.Header
}))
defer server.Close()
homeKey := homedir.Key()
homeVal := homedir.Get()
tmpDir, err := ioutil.TempDir("", "fake-home")
c.Assert(err, checker.IsNil)
defer os.RemoveAll(tmpDir)
dotDocker := filepath.Join(tmpDir, ".docker")
os.Mkdir(dotDocker, 0600)
tmpCfg := filepath.Join(dotDocker, "config.json")
defer func() { os.Setenv(homeKey, homeVal) }()
os.Setenv(homeKey, tmpDir)
data := `{
"HttpHeaders": { "MyHeader": "MyValue" }
}`
err = ioutil.WriteFile(tmpCfg, []byte(data), 0600)
c.Assert(err, checker.IsNil)
result := icmd.RunCommand(dockerBinary, "-H="+server.URL[7:], "ps")
result.Assert(c, icmd.Expected{
ExitCode: 1,
Error: "exit status 1",
})
c.Assert(headers["User-Agent"], checker.NotNil, check.Commentf("Missing User-Agent"))
c.Assert(headers["User-Agent"][0], checker.Equals, "Docker-Client/"+dockerversion.Version+" ("+runtime.GOOS+")", check.Commentf("Badly formatted User-Agent,out:%v", result.Combined()))
c.Assert(headers["Myheader"], checker.NotNil)
c.Assert(headers["Myheader"][0], checker.Equals, "MyValue", check.Commentf("Missing/bad header,out:%v", result.Combined()))
}
示例13: TestDaemonShutdownWithPlugins
// TestDaemonShutdownWithPlugins shuts down running plugins.
func (s *DockerDaemonSuite) TestDaemonShutdownWithPlugins(c *check.C) {
testRequires(c, IsAmd64, Network, SameHostDaemon)
s.d.Start(c)
if out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", pName); err != nil {
c.Fatalf("Could not install plugin: %v %s", err, out)
}
defer func() {
s.d.Restart(c)
if out, err := s.d.Cmd("plugin", "disable", pName); err != nil {
c.Fatalf("Could not disable plugin: %v %s", err, out)
}
if out, err := s.d.Cmd("plugin", "remove", pName); err != nil {
c.Fatalf("Could not remove plugin: %v %s", err, out)
}
}()
if err := s.d.Interrupt(); err != nil {
c.Fatalf("Could not kill daemon: %v", err)
}
for {
if err := syscall.Kill(s.d.Pid(), 0); err == syscall.ESRCH {
break
}
}
icmd.RunCommand("pgrep", "-f", pluginProcessName).Assert(c, icmd.Expected{
ExitCode: 1,
Error: "exit status 1",
})
s.d.Start(c, "--live-restore")
icmd.RunCommand("pgrep", "-f", pluginProcessName).Assert(c, icmd.Success)
}
示例14: TestStartAttachWithRename
// Test case for #23716
func (s *DockerSuite) TestStartAttachWithRename(c *check.C) {
testRequires(c, DaemonIsLinux)
dockerCmd(c, "create", "-t", "--name", "before", "busybox")
go func() {
c.Assert(waitRun("before"), checker.IsNil)
dockerCmd(c, "rename", "before", "after")
dockerCmd(c, "stop", "--time=2", "after")
}()
// FIXME(vdemeester) the intent is not clear and potentially racey
result := icmd.RunCommand(dockerBinary, "start", "-a", "before")
result.Assert(c, icmd.Expected{
ExitCode: 137,
Error: "exit status 137",
})
c.Assert(result.Stderr(), checker.Not(checker.Contains), "No such container")
}
示例15: testConcurrentPullWholeRepo
// testConcurrentPullWholeRepo pulls the same repo concurrently.
func testConcurrentPullWholeRepo(c *check.C) {
repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL)
repos := []string{}
for _, tag := range []string{"recent", "fresh", "todays"} {
repo := fmt.Sprintf("%v:%v", repoName, tag)
_, err := buildImage(repo, fmt.Sprintf(`
FROM busybox
ENTRYPOINT ["/bin/echo"]
ENV FOO foo
ENV BAR bar
CMD echo %s
`, repo), true)
c.Assert(err, checker.IsNil)
dockerCmd(c, "push", repo)
repos = append(repos, repo)
}
// Clear local images store.
args := append([]string{"rmi"}, repos...)
dockerCmd(c, args...)
// Run multiple re-pulls concurrently
results := make(chan error)
numPulls := 3
for i := 0; i != numPulls; i++ {
go func() {
result := icmd.RunCommand(dockerBinary, "pull", "-a", repoName)
results <- result.Error
}()
}
// These checks are separate from the loop above because the check
// package is not goroutine-safe.
for i := 0; i != numPulls; i++ {
err := <-results
c.Assert(err, checker.IsNil, check.Commentf("concurrent pull failed with error: %v", err))
}
// Ensure all tags were pulled successfully
for _, repo := range repos {
dockerCmd(c, "inspect", repo)
out, _ := dockerCmd(c, "run", "--rm", repo)
c.Assert(strings.TrimSpace(out), checker.Equals, "/bin/sh -c echo "+repo)
}
}