func TestOldInvalidsAuth(t *testing.T) { invalids := map[string]string{ `username = test`: "The Auth config file is empty", `username password`: "Invalid Auth config file", `username = test email`: "Invalid auth configuration file", } tmpHome, err := ioutil.TempDir("", "config-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpHome) homeKey := homedir.Key() homeVal := homedir.Get() defer func() { os.Setenv(homeKey, homeVal) }() os.Setenv(homeKey, tmpHome) for content, expectedError := range invalids { fn := filepath.Join(tmpHome, oldConfigfile) if err := ioutil.WriteFile(fn, []byte(content), 0600); err != nil { t.Fatal(err) } config, err := Load(tmpHome) // Use Contains instead of == since the file name will change each time if err == nil || !strings.Contains(err.Error(), expectedError) { t.Fatalf("Should have failed\nConfig: %v\nGot: %v\nExpected: %v", config, err, expectedError) } } }
func TestOldJSONInvalid(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpHome) homeKey := homedir.Key() homeVal := homedir.Get() defer func() { os.Setenv(homeKey, homeVal) }() os.Setenv(homeKey, tmpHome) fn := filepath.Join(tmpHome, oldConfigfile) js := `{"https://index.docker.io/v1/":{"auth":"test","email":"*****@*****.**"}}` if err := ioutil.WriteFile(fn, []byte(js), 0600); err != nil { t.Fatal(err) } config, err := Load(tmpHome) // Use Contains instead of == since the file name will change each time if err == nil || !strings.Contains(err.Error(), "Invalid auth configuration file") { t.Fatalf("Expected an error got : %v, %v", config, err) } }
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) { headers = r.Header })) defer server.Close() homeKey := homedir.Key() homeVal := homedir.Get() tmpDir, err := ioutil.TempDir("", "fake-home") c.Assert(err, check.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) if err != nil { c.Fatalf("Err creating file(%s): %v", tmpCfg, err) } cmd := exec.Command(dockerBinary, "-H="+server.URL[7:], "ps") out, _, _ := runCommandWithOutput(cmd) if headers["User-Agent"] == nil { c.Fatalf("Missing User-Agent: %q\nout:%v", headers, out) } if headers["User-Agent"][0] != "Docker-Client/"+dockerversion.VERSION+" ("+runtime.GOOS+")" { c.Fatalf("Badly formatted User-Agent: %q\nout:%v", headers, out) } if headers["Myheader"] == nil || headers["Myheader"][0] != "MyValue" { c.Fatalf("Missing/bad header: %q\nout:%v", headers, out) } }
func TestOldValidAuth(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") if err != nil { t.Fatal(err) } if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpHome) homeKey := homedir.Key() homeVal := homedir.Get() defer func() { os.Setenv(homeKey, homeVal) }() os.Setenv(homeKey, tmpHome) fn := filepath.Join(tmpHome, oldConfigfile) js := `username = am9lam9lOmhlbGxv email = [email protected]` if err := ioutil.WriteFile(fn, []byte(js), 0600); err != nil { t.Fatal(err) } config, err := Load(tmpHome) if err != nil { t.Fatal(err) } // defaultIndexserver is https://index.docker.io/v1/ ac := config.AuthConfigs["https://index.docker.io/v1/"] if ac.Username != "joejoe" || ac.Password != "hello" { t.Fatalf("Missing data from parsing:\n%q", config) } // Now save it and make sure it shows up in new form configStr := saveConfigAndValidateNewFormat(t, config, tmpHome) expConfStr := `{ "auths": { "https://index.docker.io/v1/": { "auth": "am9lam9lOmhlbGxv" } } }` if configStr != expConfStr { t.Fatalf("Should have save in new form: \n%s\n not \n%s", configStr, expConfStr) } }
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())) }
func FixHOME(app *cli.App) { appBefore := app.Before app.Before = func(c *cli.Context) error { // Fix home if key := homedir.Key(); os.Getenv(key) == "" { value := homedir.Get() if value == "" { return fmt.Errorf("the %q is not set", key) } os.Setenv(key, value) } if appBefore != nil { return appBefore(c) } return nil } }
func TestOldJson(t *testing.T) { if runtime.GOOS == "windows" { return } tmpHome, _ := ioutil.TempDir("", "config-test") defer os.RemoveAll(tmpHome) homeKey := homedir.Key() homeVal := homedir.Get() defer func() { os.Setenv(homeKey, homeVal) }() os.Setenv(homeKey, tmpHome) fn := filepath.Join(tmpHome, OLD_CONFIGFILE) js := `{"https://index.docker.io/v1/":{"auth":"am9lam9lOmhlbGxv","email":"*****@*****.**"}}` ioutil.WriteFile(fn, []byte(js), 0600) config, err := Load(tmpHome) if err != nil { t.Fatalf("Failed loading on empty json file: %q", err) } ac := config.AuthConfigs["https://index.docker.io/v1/"] if ac.Email != "*****@*****.**" || ac.Username != "joejoe" || ac.Password != "hello" { t.Fatalf("Missing data from parsing:\n%q", config) } // Now save it and make sure it shows up in new form err = config.Save() if err != nil { t.Fatalf("Failed to save: %q", err) } buf, err := ioutil.ReadFile(filepath.Join(tmpHome, CONFIGFILE)) if !strings.Contains(string(buf), `"auths":`) || !strings.Contains(string(buf), "*****@*****.**") { t.Fatalf("Should have save in new form: %s", string(buf)) } }
func TestOldInvalidsAuth(t *testing.T) { invalids := map[string]string{ `username = test`: "The Auth config file is empty", `username password email`: "Invalid Auth config file", `username = test email`: "Invalid auth configuration file", `username = am9lam9lOmhlbGxv email`: "Invalid Auth config file", } tmpHome, err := ioutil.TempDir("", "config-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpHome) homeKey := homedir.Key() homeVal := homedir.Get() defer func() { os.Setenv(homeKey, homeVal) }() os.Setenv(homeKey, tmpHome) for content, expectedError := range invalids { fn := filepath.Join(tmpHome, oldConfigfile) if err := ioutil.WriteFile(fn, []byte(content), 0600); err != nil { t.Fatal(err) } config, err := Load(tmpHome) if err == nil || err.Error() != expectedError { t.Fatalf("Should have failed, got: %q, %q", config, err) } } }
func TestOldJson(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpHome) homeKey := homedir.Key() homeVal := homedir.Get() defer func() { os.Setenv(homeKey, homeVal) }() os.Setenv(homeKey, tmpHome) fn := filepath.Join(tmpHome, oldConfigfile) js := `{"https://index.docker.io/v1/":{"auth":"am9lam9lOmhlbGxv","email":"*****@*****.**"}}` if err := ioutil.WriteFile(fn, []byte(js), 0600); err != nil { t.Fatal(err) } config, err := Load(tmpHome) if err != nil { t.Fatalf("Failed loading on empty json file: %q", err) } ac := config.AuthConfigs["https://index.docker.io/v1/"] if ac.Email != "*****@*****.**" || ac.Username != "joejoe" || ac.Password != "hello" { t.Fatalf("Missing data from parsing:\n%q", config) } // Now save it and make sure it shows up in new form configStr := saveConfigAndValidateNewFormat(t, config, tmpHome) if !strings.Contains(configStr, "*****@*****.**") { t.Fatalf("Should have save in new form: %s", configStr) } }
// TestRunDetach checks attaching and detaching with the detach flags, making sure it overrides config file func (s *DockerSuite) TestRunAttachDetachKeysOverrideConfig(c *check.C) { keyCtrlA := []byte{1} keyA := []byte{97} // Setup config 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 := `{ "detachKeys": "ctrl-e,e" }` err = ioutil.WriteFile(tmpCfg, []byte(data), 0600) c.Assert(err, checker.IsNil) // Then do the work name := "attach-detach" dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") cmd := exec.Command(dockerBinary, "attach", "--detach-keys='ctrl-a,a'", name) stdout, err := cmd.StdoutPipe() if err != nil { c.Fatal(err) } cpty, tty, err := pty.Open() if err != nil { c.Fatal(err) } defer cpty.Close() cmd.Stdin = tty if err := cmd.Start(); err != nil { c.Fatal(err) } c.Assert(waitRun(name), check.IsNil) if _, err := cpty.Write([]byte("hello\n")); err != nil { c.Fatal(err) } out, err := bufio.NewReader(stdout).ReadString('\n') if err != nil { c.Fatal(err) } if strings.TrimSpace(out) != "hello" { c.Fatalf("expected 'hello', got %q", out) } // escape sequence if _, err := cpty.Write(keyCtrlA); err != nil { c.Fatal(err) } time.Sleep(100 * time.Millisecond) if _, err := cpty.Write(keyA); err != nil { c.Fatal(err) } ch := make(chan struct{}) go func() { cmd.Wait() ch <- struct{}{} }() select { case <-ch: case <-time.After(10 * time.Second): c.Fatal("timed out waiting for container to exit") } running := inspectField(c, name, "State.Running") c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running")) }
func (s *DockerSuite) TestHelpTextVerify(c *check.C) { testRequires(c, DaemonIsLinux) // Make sure main help text fits within 80 chars and that // on non-windows system we use ~ when possible (to shorten things). // Test for HOME set to its default value and set to "/" on linux // Yes on windows setting up an array and looping (right now) isn't // necessary because we just have one value, but we'll need the // array/loop on linux so we might as well set it up so that we can // test any number of home dirs later on and all we need to do is // modify the array - the rest of the testing infrastructure should work homes := []string{homedir.Get()} // Non-Windows machines need to test for this special case of $HOME if runtime.GOOS != "windows" { homes = append(homes, "/") } homeKey := homedir.Key() baseEnvs := appendBaseEnv(true) // Remove HOME env var from list so we can add a new value later. for i, env := range baseEnvs { if strings.HasPrefix(env, homeKey+"=") { baseEnvs = append(baseEnvs[:i], baseEnvs[i+1:]...) break } } for _, home := range homes { // Dup baseEnvs and add our new HOME value newEnvs := make([]string, len(baseEnvs)+1) copy(newEnvs, baseEnvs) newEnvs[len(newEnvs)-1] = homeKey + "=" + home scanForHome := runtime.GOOS != "windows" && home != "/" // Check main help text to make sure its not over 80 chars helpCmd := exec.Command(dockerBinary, "help") helpCmd.Env = newEnvs out, _, err := runCommandWithOutput(helpCmd) c.Assert(err, checker.IsNil, check.Commentf(out)) lines := strings.Split(out, "\n") foundTooLongLine := false for _, line := range lines { if !foundTooLongLine && len(line) > 80 { c.Logf("Line is too long:\n%s", line) foundTooLongLine = true } // All lines should not end with a space c.Assert(line, checker.Not(checker.HasSuffix), " ", check.Commentf("Line should not end with a space")) if scanForHome && strings.Contains(line, `=`+home) { c.Fatalf("Line should use '%q' instead of %q:\n%s", homedir.GetShortcutString(), home, line) } if runtime.GOOS != "windows" { i := strings.Index(line, homedir.GetShortcutString()) if i >= 0 && i != len(line)-1 && line[i+1] != '/' { c.Fatalf("Main help should not have used home shortcut:\n%s", line) } } } // Make sure each cmd's help text fits within 90 chars and that // on non-windows system we use ~ when possible (to shorten things). // Pull the list of commands from the "Commands:" section of docker help helpCmd = exec.Command(dockerBinary, "help") helpCmd.Env = newEnvs out, _, err = runCommandWithOutput(helpCmd) c.Assert(err, checker.IsNil, check.Commentf(out)) i := strings.Index(out, "Commands:") c.Assert(i, checker.GreaterOrEqualThan, 0, check.Commentf("Missing 'Commands:' in:\n%s", out)) cmds := []string{} // Grab all chars starting at "Commands:" helpOut := strings.Split(out[i:], "\n") // First line is just "Commands:" if isLocalDaemon { // Replace first line with "daemon" command since it's not part of the list of commands. helpOut[0] = " daemon" } else { // Skip first line helpOut = helpOut[1:] } // Create the list of commands we want to test cmdsToTest := []string{} for _, cmd := range helpOut { // Stop on blank line or non-idented line if cmd == "" || !unicode.IsSpace(rune(cmd[0])) { break } // Grab just the first word of each line cmd = strings.Split(strings.TrimSpace(cmd), " ")[0] cmds = append(cmds, cmd) // Saving count for later cmdsToTest = append(cmdsToTest, cmd) } // Add some 'two word' commands - would be nice to automatically // calculate this list - somehow cmdsToTest = append(cmdsToTest, "volume create") cmdsToTest = append(cmdsToTest, "volume inspect") cmdsToTest = append(cmdsToTest, "volume ls") cmdsToTest = append(cmdsToTest, "volume rm") // Divide the list of commands into go routines and run the func testcommand on the commands in parallel // to save runtime of test errChan := make(chan error) for index := 0; index < len(cmdsToTest); index++ { go func(index int) { errChan <- testCommand(cmdsToTest[index], newEnvs, scanForHome, home) }(index) } for index := 0; index < len(cmdsToTest); index++ { err := <-errChan if err != nil { c.Fatal(err) } } // Number of commands for standard release and experimental release standard := 41 experimental := 1 expected := standard + experimental if isLocalDaemon { expected++ // for the daemon command } c.Assert(len(cmds), checker.LessOrEqualThan, expected, check.Commentf("Wrong # of cmds, it should be: %d\nThe list:\n%q", expected, cmds)) } }
func TestHelpTextVerify(t *testing.T) { // Make sure main help text fits within 80 chars and that // on non-windows system we use ~ when possible (to shorten things). // Test for HOME set to its default value and set to "/" on linux // Yes on windows setting up an array and looping (right now) isn't // necessary because we just have one value, but we'll need the // array/loop on linux so we might as well set it up so that we can // test any number of home dirs later on and all we need to do is // modify the array - the rest of the testing infrastructure should work homes := []string{homedir.Get()} // Non-Windows machines need to test for this special case of $HOME if runtime.GOOS != "windows" { homes = append(homes, "/") } homeKey := homedir.Key() baseEnvs := os.Environ() // Remove HOME env var from list so we can add a new value later. for i, env := range baseEnvs { if strings.HasPrefix(env, homeKey+"=") { baseEnvs = append(baseEnvs[:i], baseEnvs[i+1:]...) break } } for _, home := range homes { // Dup baseEnvs and add our new HOME value newEnvs := make([]string, len(baseEnvs)+1) copy(newEnvs, baseEnvs) newEnvs[len(newEnvs)-1] = homeKey + "=" + home scanForHome := runtime.GOOS != "windows" && home != "/" // Check main help text to make sure its not over 80 chars helpCmd := exec.Command(dockerBinary, "help") helpCmd.Env = newEnvs out, ec, err := runCommandWithOutput(helpCmd) if err != nil || ec != 0 { t.Fatalf("docker help should have worked\nout:%s\nec:%d", out, ec) } lines := strings.Split(out, "\n") for _, line := range lines { if len(line) > 80 { t.Fatalf("Line is too long(%d chars):\n%s", len(line), line) } // All lines should not end with a space if strings.HasSuffix(line, " ") { t.Fatalf("Line should not end with a space: %s", line) } if scanForHome && strings.Contains(line, `=`+home) { t.Fatalf("Line should use '%q' instead of %q:\n%s", homedir.GetShortcutString(), home, line) } if runtime.GOOS != "windows" { i := strings.Index(line, homedir.GetShortcutString()) if i >= 0 && i != len(line)-1 && line[i+1] != '/' { t.Fatalf("Main help should not have used home shortcut:\n%s", line) } } } // Make sure each cmd's help text fits within 80 chars and that // on non-windows system we use ~ when possible (to shorten things). // Pull the list of commands from the "Commands:" section of docker help helpCmd = exec.Command(dockerBinary, "help") helpCmd.Env = newEnvs out, ec, err = runCommandWithOutput(helpCmd) if err != nil || ec != 0 { t.Fatalf("docker help should have worked\nout:%s\nec:%d", out, ec) } i := strings.Index(out, "Commands:") if i < 0 { t.Fatalf("Missing 'Commands:' in:\n%s", out) } // Grab all chars starting at "Commands:" // Skip first line, its "Commands:" cmds := []string{} for _, cmd := range strings.Split(out[i:], "\n")[1:] { // Stop on blank line or non-idented line if cmd == "" || !unicode.IsSpace(rune(cmd[0])) { break } // Grab just the first word of each line cmd = strings.Split(strings.TrimSpace(cmd), " ")[0] cmds = append(cmds, cmd) helpCmd := exec.Command(dockerBinary, cmd, "--help") helpCmd.Env = newEnvs out, ec, err := runCommandWithOutput(helpCmd) if err != nil || ec != 0 { t.Fatalf("Error on %q help: %s\nexit code:%d", cmd, out, ec) } lines := strings.Split(out, "\n") for _, line := range lines { if len(line) > 80 { t.Fatalf("Help for %q is too long(%d chars):\n%s", cmd, len(line), line) } if scanForHome && strings.Contains(line, `"`+home) { t.Fatalf("Help for %q should use ~ instead of %q on:\n%s", cmd, home, line) } i := strings.Index(line, "~") if i >= 0 && i != len(line)-1 && line[i+1] != '/' { t.Fatalf("Help for %q should not have used ~:\n%s", cmd, line) } // If a line starts with 4 spaces then assume someone // added a multi-line description for an option and we need // to flag it if strings.HasPrefix(line, " ") { t.Fatalf("Help for %q should not have a multi-line option: %s", cmd, line) } // Options should NOT end with a period if strings.HasPrefix(line, " -") && strings.HasSuffix(line, ".") { t.Fatalf("Help for %q should not end with a period: %s", cmd, line) } // Options should NOT end with a space if strings.HasSuffix(line, " ") { t.Fatalf("Help for %q should not end with a space: %s", cmd, line) } } } expected := 39 if len(cmds) != expected { t.Fatalf("Wrong # of cmds(%d), it should be: %d\nThe list:\n%q", len(cmds), expected, cmds) } } logDone("help - verify text") }
func (s *DockerSuite) TestHelpTextVerify(c *check.C) { testRequires(c, DaemonIsLinux) // Make sure main help text fits within 80 chars and that // on non-windows system we use ~ when possible (to shorten things). // Test for HOME set to its default value and set to "/" on linux // Yes on windows setting up an array and looping (right now) isn't // necessary because we just have one value, but we'll need the // array/loop on linux so we might as well set it up so that we can // test any number of home dirs later on and all we need to do is // modify the array - the rest of the testing infrastructure should work homes := []string{homedir.Get()} // Non-Windows machines need to test for this special case of $HOME if runtime.GOOS != "windows" { homes = append(homes, "/") } homeKey := homedir.Key() baseEnvs := os.Environ() // Remove HOME env var from list so we can add a new value later. for i, env := range baseEnvs { if strings.HasPrefix(env, homeKey+"=") { baseEnvs = append(baseEnvs[:i], baseEnvs[i+1:]...) break } } for _, home := range homes { // Dup baseEnvs and add our new HOME value newEnvs := make([]string, len(baseEnvs)+1) copy(newEnvs, baseEnvs) newEnvs[len(newEnvs)-1] = homeKey + "=" + home scanForHome := runtime.GOOS != "windows" && home != "/" // Check main help text to make sure its not over 80 chars helpCmd := exec.Command(dockerBinary, "help") helpCmd.Env = newEnvs out, _, err := runCommandWithOutput(helpCmd) c.Assert(err, checker.IsNil, check.Commentf(out)) lines := strings.Split(out, "\n") for _, line := range lines { c.Assert(len(line), checker.LessOrEqualThan, 80, check.Commentf("Line is too long:\n%s", line)) // All lines should not end with a space c.Assert(line, checker.Not(checker.HasSuffix), " ", check.Commentf("Line should not end with a space")) if scanForHome && strings.Contains(line, `=`+home) { c.Fatalf("Line should use '%q' instead of %q:\n%s", homedir.GetShortcutString(), home, line) } if runtime.GOOS != "windows" { i := strings.Index(line, homedir.GetShortcutString()) if i >= 0 && i != len(line)-1 && line[i+1] != '/' { c.Fatalf("Main help should not have used home shortcut:\n%s", line) } } } // Make sure each cmd's help text fits within 90 chars and that // on non-windows system we use ~ when possible (to shorten things). // Pull the list of commands from the "Commands:" section of docker help helpCmd = exec.Command(dockerBinary, "help") helpCmd.Env = newEnvs out, _, err = runCommandWithOutput(helpCmd) c.Assert(err, checker.IsNil, check.Commentf(out)) i := strings.Index(out, "Commands:") c.Assert(i, checker.GreaterOrEqualThan, 0, check.Commentf("Missing 'Commands:' in:\n%s", out)) cmds := []string{} // Grab all chars starting at "Commands:" helpOut := strings.Split(out[i:], "\n") // First line is just "Commands:" if isLocalDaemon { // Replace first line with "daemon" command since it's not part of the list of commands. helpOut[0] = " daemon" } else { // Skip first line helpOut = helpOut[1:] } // Create the list of commands we want to test cmdsToTest := []string{} for _, cmd := range helpOut { // Stop on blank line or non-idented line if cmd == "" || !unicode.IsSpace(rune(cmd[0])) { break } // Grab just the first word of each line cmd = strings.Split(strings.TrimSpace(cmd), " ")[0] cmds = append(cmds, cmd) // Saving count for later cmdsToTest = append(cmdsToTest, cmd) } // Add some 'two word' commands - would be nice to automatically // calculate this list - somehow cmdsToTest = append(cmdsToTest, "volume create") cmdsToTest = append(cmdsToTest, "volume inspect") cmdsToTest = append(cmdsToTest, "volume ls") cmdsToTest = append(cmdsToTest, "volume rm") for _, cmd := range cmdsToTest { var stderr string args := strings.Split(cmd+" --help", " ") // Check the full usage text helpCmd := exec.Command(dockerBinary, args...) helpCmd.Env = newEnvs out, stderr, _, err = runCommandWithStdoutStderr(helpCmd) c.Assert(len(stderr), checker.Equals, 0, check.Commentf("Error on %q help. non-empty stderr:%q", cmd, stderr)) c.Assert(out, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have blank line on %q\n", cmd)) c.Assert(out, checker.Contains, "--help=false", check.Commentf("Should show full usage on %q\n", cmd)) c.Assert(err, checker.IsNil, check.Commentf(out)) // Check each line for lots of stuff lines := strings.Split(out, "\n") for _, line := range lines { c.Assert(len(line), checker.LessOrEqualThan, 90, check.Commentf("Help for %q is too long:\n%s", cmd, line)) if scanForHome && strings.Contains(line, `"`+home) { c.Fatalf("Help for %q should use ~ instead of %q on:\n%s", cmd, home, line) } i := strings.Index(line, "~") if i >= 0 && i != len(line)-1 && line[i+1] != '/' { c.Fatalf("Help for %q should not have used ~:\n%s", cmd, line) } // If a line starts with 4 spaces then assume someone // added a multi-line description for an option and we need // to flag it c.Assert(line, checker.Not(checker.HasPrefix), " ", check.Commentf("Help for %q should not have a multi-line option", cmd)) // Options should NOT end with a period if strings.HasPrefix(line, " -") && strings.HasSuffix(line, ".") { c.Fatalf("Help for %q should not end with a period: %s", cmd, line) } // Options should NOT end with a space c.Assert(line, checker.Not(checker.HasSuffix), " ", check.Commentf("Help for %q should not end with a space", cmd)) } // For each command make sure we generate an error // if we give a bad arg args = strings.Split(cmd+" --badArg", " ") out, _, err = dockerCmdWithError(args...) c.Assert(err, checker.NotNil, check.Commentf(out)) // Be really picky c.Assert(stderr, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have a blank line at the end of 'docker rm'\n")) // Now make sure that each command will print a short-usage // (not a full usage - meaning no opts section) if we // are missing a required arg or pass in a bad arg // These commands will never print a short-usage so don't test noShortUsage := map[string]string{ "images": "", "login": "", "logout": "", "network": "", "stats": "", } if _, ok := noShortUsage[cmd]; !ok { // For each command run it w/o any args. It will either return // valid output or print a short-usage var dCmd *exec.Cmd var stdout, stderr string var args []string // skipNoArgs are ones that we don't want to try w/o // any args. Either because it'll hang the test or // lead to incorrect test result (like false negative). // Whatever the reason, skip trying to run w/o args and // jump to trying with a bogus arg. skipNoArgs := map[string]struct{}{ "daemon": {}, "events": {}, "load": {}, } ec := 0 if _, ok := skipNoArgs[cmd]; !ok { args = strings.Split(cmd, " ") dCmd = exec.Command(dockerBinary, args...) stdout, stderr, ec, err = runCommandWithStdoutStderr(dCmd) } // If its ok w/o any args then try again with an arg if ec == 0 { args = strings.Split(cmd+" badArg", " ") dCmd = exec.Command(dockerBinary, args...) stdout, stderr, ec, err = runCommandWithStdoutStderr(dCmd) } if len(stdout) != 0 || len(stderr) == 0 || ec == 0 || err == nil { c.Fatalf("Bad output from %q\nstdout:%q\nstderr:%q\nec:%d\nerr:%q", args, stdout, stderr, ec, err) } // Should have just short usage c.Assert(stderr, checker.Contains, "\nUsage:\t", check.Commentf("Missing short usage on %q\n", args)) // But shouldn't have full usage c.Assert(stderr, checker.Not(checker.Contains), "--help=false", check.Commentf("Should not have full usage on %q\n", args)) c.Assert(stderr, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have a blank line on %q\n", args)) } } // Number of commands for standard release and experimental release standard := 40 experimental := 1 expected := standard + experimental if isLocalDaemon { expected++ // for the daemon command } c.Assert(len(cmds), checker.LessOrEqualThan, expected, check.Commentf("Wrong # of cmds, it should be: %d\nThe list:\n%q", expected, cmds)) } }
func (s *DockerSuite) TestHelpTextVerify(c *check.C) { // Make sure main help text fits within 80 chars and that // on non-windows system we use ~ when possible (to shorten things). // Test for HOME set to its default value and set to "/" on linux // Yes on windows setting up an array and looping (right now) isn't // necessary because we just have one value, but we'll need the // array/loop on linux so we might as well set it up so that we can // test any number of home dirs later on and all we need to do is // modify the array - the rest of the testing infrastructure should work homes := []string{homedir.Get()} // Non-Windows machines need to test for this special case of $HOME if runtime.GOOS != "windows" { homes = append(homes, "/") } homeKey := homedir.Key() baseEnvs := os.Environ() // Remove HOME env var from list so we can add a new value later. for i, env := range baseEnvs { if strings.HasPrefix(env, homeKey+"=") { baseEnvs = append(baseEnvs[:i], baseEnvs[i+1:]...) break } } for _, home := range homes { // Dup baseEnvs and add our new HOME value newEnvs := make([]string, len(baseEnvs)+1) copy(newEnvs, baseEnvs) newEnvs[len(newEnvs)-1] = homeKey + "=" + home scanForHome := runtime.GOOS != "windows" && home != "/" // Check main help text to make sure its not over 80 chars helpCmd := exec.Command(dockerBinary, "help") helpCmd.Env = newEnvs out, ec, err := runCommandWithOutput(helpCmd) if err != nil || ec != 0 { c.Fatalf("docker help should have worked\nout:%s\nec:%d", out, ec) } lines := strings.Split(out, "\n") for _, line := range lines { if len(line) > 80 { c.Fatalf("Line is too long(%d chars):\n%s", len(line), line) } // All lines should not end with a space if strings.HasSuffix(line, " ") { c.Fatalf("Line should not end with a space: %s", line) } if scanForHome && strings.Contains(line, `=`+home) { c.Fatalf("Line should use '%q' instead of %q:\n%s", homedir.GetShortcutString(), home, line) } if runtime.GOOS != "windows" { i := strings.Index(line, homedir.GetShortcutString()) if i >= 0 && i != len(line)-1 && line[i+1] != '/' { c.Fatalf("Main help should not have used home shortcut:\n%s", line) } } } // Make sure each cmd's help text fits within 80 chars and that // on non-windows system we use ~ when possible (to shorten things). // Pull the list of commands from the "Commands:" section of docker help helpCmd = exec.Command(dockerBinary, "help") helpCmd.Env = newEnvs out, ec, err = runCommandWithOutput(helpCmd) if err != nil || ec != 0 { c.Fatalf("docker help should have worked\nout:%s\nec:%d", out, ec) } i := strings.Index(out, "Commands:") if i < 0 { c.Fatalf("Missing 'Commands:' in:\n%s", out) } // Grab all chars starting at "Commands:" // Skip first line, its "Commands:" cmds := []string{} for _, cmd := range strings.Split(out[i:], "\n")[1:] { var stderr string // Stop on blank line or non-idented line if cmd == "" || !unicode.IsSpace(rune(cmd[0])) { break } // Grab just the first word of each line cmd = strings.Split(strings.TrimSpace(cmd), " ")[0] cmds = append(cmds, cmd) // Check the full usage text helpCmd := exec.Command(dockerBinary, cmd, "--help") helpCmd.Env = newEnvs out, stderr, ec, err = runCommandWithStdoutStderr(helpCmd) if len(stderr) != 0 { c.Fatalf("Error on %q help. non-empty stderr:%q", cmd, stderr) } if strings.HasSuffix(out, "\n\n") { c.Fatalf("Should not have blank line on %q\nout:%q", cmd, out) } if !strings.Contains(out, "--help=false") { c.Fatalf("Should show full usage on %q\nout:%q", cmd, out) } if err != nil || ec != 0 { c.Fatalf("Error on %q help: %s\nexit code:%d", cmd, out, ec) } // Check each line for lots of stuff lines := strings.Split(out, "\n") for _, line := range lines { if len(line) > 80 { c.Fatalf("Help for %q is too long(%d chars):\n%s", cmd, len(line), line) } if scanForHome && strings.Contains(line, `"`+home) { c.Fatalf("Help for %q should use ~ instead of %q on:\n%s", cmd, home, line) } i := strings.Index(line, "~") if i >= 0 && i != len(line)-1 && line[i+1] != '/' { c.Fatalf("Help for %q should not have used ~:\n%s", cmd, line) } // If a line starts with 4 spaces then assume someone // added a multi-line description for an option and we need // to flag it if strings.HasPrefix(line, " ") { c.Fatalf("Help for %q should not have a multi-line option: %s", cmd, line) } // Options should NOT end with a period if strings.HasPrefix(line, " -") && strings.HasSuffix(line, ".") { c.Fatalf("Help for %q should not end with a period: %s", cmd, line) } // Options should NOT end with a space if strings.HasSuffix(line, " ") { c.Fatalf("Help for %q should not end with a space: %s", cmd, line) } } // For each command make sure we generate an error // if we give a bad arg dCmd := exec.Command(dockerBinary, cmd, "--badArg") out, stderr, ec, err = runCommandWithStdoutStderr(dCmd) if len(out) != 0 || len(stderr) == 0 || ec == 0 || err == nil { c.Fatalf("Bad results from 'docker %s --badArg'\nec:%d\nstdout:%s\nstderr:%s\nerr:%q", cmd, ec, out, stderr, err) } // Be really picky if strings.HasSuffix(stderr, "\n\n") { c.Fatalf("Should not have a blank line at the end of 'docker rm'\n%s", stderr) } // Now make sure that each command will print a short-usage // (not a full usage - meaning no opts section) if we // are missing a required arg or pass in a bad arg // These commands will never print a short-usage so don't test noShortUsage := map[string]string{ "images": "", "login": "", "logout": "", } if _, ok := noShortUsage[cmd]; !ok { // For each command run it w/o any args. It will either return // valid output or print a short-usage var dCmd *exec.Cmd var stdout, stderr string var args []string // skipNoArgs are ones that we don't want to try w/o // any args. Either because it'll hang the test or // lead to incorrect test result (like false negative). // Whatever the reason, skip trying to run w/o args and // jump to trying with a bogus arg. skipNoArgs := map[string]string{ "events": "", "load": "", } ec = 0 if _, ok := skipNoArgs[cmd]; !ok { args = []string{cmd} dCmd = exec.Command(dockerBinary, args...) stdout, stderr, ec, err = runCommandWithStdoutStderr(dCmd) } // If its ok w/o any args then try again with an arg if ec == 0 { args = []string{cmd, "badArg"} dCmd = exec.Command(dockerBinary, args...) stdout, stderr, ec, err = runCommandWithStdoutStderr(dCmd) } if len(stdout) != 0 || len(stderr) == 0 || ec == 0 || err == nil { c.Fatalf("Bad output from %q\nstdout:%q\nstderr:%q\nec:%d\nerr:%q", args, stdout, stderr, ec, err) } // Should have just short usage if !strings.Contains(stderr, "\nUsage: ") { c.Fatalf("Missing short usage on %q\nstderr:%q", args, stderr) } // But shouldn't have full usage if strings.Contains(stderr, "--help=false") { c.Fatalf("Should not have full usage on %q\nstderr:%q", args, stderr) } if strings.HasSuffix(stderr, "\n\n") { c.Fatalf("Should not have a blank line on %q\nstderr:%q", args, stderr) } } } expected := 39 if len(cmds) != expected { c.Fatalf("Wrong # of cmds(%d), it should be: %d\nThe list:\n%q", len(cmds), expected, cmds) } } }