docker_cli_help_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. package main
  2. import (
  3. "fmt"
  4. "runtime"
  5. "strings"
  6. "unicode"
  7. "github.com/docker/docker/integration-cli/checker"
  8. "github.com/docker/docker/pkg/homedir"
  9. icmd "github.com/docker/docker/pkg/testutil/cmd"
  10. "github.com/go-check/check"
  11. )
  12. func (s *DockerSuite) TestHelpTextVerify(c *check.C) {
  13. // FIXME(vdemeester) should be a unit test, probably using golden files ?
  14. testRequires(c, DaemonIsLinux)
  15. // Make sure main help text fits within 80 chars and that
  16. // on non-windows system we use ~ when possible (to shorten things).
  17. // Test for HOME set to its default value and set to "/" on linux
  18. // Yes on windows setting up an array and looping (right now) isn't
  19. // necessary because we just have one value, but we'll need the
  20. // array/loop on linux so we might as well set it up so that we can
  21. // test any number of home dirs later on and all we need to do is
  22. // modify the array - the rest of the testing infrastructure should work
  23. homes := []string{homedir.Get()}
  24. // Non-Windows machines need to test for this special case of $HOME
  25. if runtime.GOOS != "windows" {
  26. homes = append(homes, "/")
  27. }
  28. homeKey := homedir.Key()
  29. baseEnvs := appendBaseEnv(true)
  30. // Remove HOME env var from list so we can add a new value later.
  31. for i, env := range baseEnvs {
  32. if strings.HasPrefix(env, homeKey+"=") {
  33. baseEnvs = append(baseEnvs[:i], baseEnvs[i+1:]...)
  34. break
  35. }
  36. }
  37. for _, home := range homes {
  38. // Dup baseEnvs and add our new HOME value
  39. newEnvs := make([]string, len(baseEnvs)+1)
  40. copy(newEnvs, baseEnvs)
  41. newEnvs[len(newEnvs)-1] = homeKey + "=" + home
  42. scanForHome := runtime.GOOS != "windows" && home != "/"
  43. // Check main help text to make sure its not over 80 chars
  44. result := icmd.RunCmd(icmd.Cmd{
  45. Command: []string{dockerBinary, "help"},
  46. Env: newEnvs,
  47. })
  48. result.Assert(c, icmd.Success)
  49. lines := strings.Split(result.Combined(), "\n")
  50. for _, line := range lines {
  51. // All lines should not end with a space
  52. c.Assert(line, checker.Not(checker.HasSuffix), " ", check.Commentf("Line should not end with a space"))
  53. if scanForHome && strings.Contains(line, `=`+home) {
  54. c.Fatalf("Line should use '%q' instead of %q:\n%s", homedir.GetShortcutString(), home, line)
  55. }
  56. if runtime.GOOS != "windows" {
  57. i := strings.Index(line, homedir.GetShortcutString())
  58. if i >= 0 && i != len(line)-1 && line[i+1] != '/' {
  59. c.Fatalf("Main help should not have used home shortcut:\n%s", line)
  60. }
  61. }
  62. }
  63. // Make sure each cmd's help text fits within 90 chars and that
  64. // on non-windows system we use ~ when possible (to shorten things).
  65. // Pull the list of commands from the "Commands:" section of docker help
  66. // FIXME(vdemeester) Why re-run help ?
  67. //helpCmd = exec.Command(dockerBinary, "help")
  68. //helpCmd.Env = newEnvs
  69. //out, _, err = runCommandWithOutput(helpCmd)
  70. //c.Assert(err, checker.IsNil, check.Commentf(out))
  71. i := strings.Index(result.Combined(), "Commands:")
  72. c.Assert(i, checker.GreaterOrEqualThan, 0, check.Commentf("Missing 'Commands:' in:\n%s", result.Combined()))
  73. cmds := []string{}
  74. // Grab all chars starting at "Commands:"
  75. helpOut := strings.Split(result.Combined()[i:], "\n")
  76. // Skip first line, it is just "Commands:"
  77. helpOut = helpOut[1:]
  78. // Create the list of commands we want to test
  79. cmdsToTest := []string{}
  80. for _, cmd := range helpOut {
  81. // Stop on blank line or non-indented line
  82. if cmd == "" || !unicode.IsSpace(rune(cmd[0])) {
  83. break
  84. }
  85. // Grab just the first word of each line
  86. cmd = strings.Split(strings.TrimSpace(cmd), " ")[0]
  87. cmds = append(cmds, cmd) // Saving count for later
  88. cmdsToTest = append(cmdsToTest, cmd)
  89. }
  90. // Add some 'two word' commands - would be nice to automatically
  91. // calculate this list - somehow
  92. cmdsToTest = append(cmdsToTest, "volume create")
  93. cmdsToTest = append(cmdsToTest, "volume inspect")
  94. cmdsToTest = append(cmdsToTest, "volume ls")
  95. cmdsToTest = append(cmdsToTest, "volume rm")
  96. cmdsToTest = append(cmdsToTest, "network connect")
  97. cmdsToTest = append(cmdsToTest, "network create")
  98. cmdsToTest = append(cmdsToTest, "network disconnect")
  99. cmdsToTest = append(cmdsToTest, "network inspect")
  100. cmdsToTest = append(cmdsToTest, "network ls")
  101. cmdsToTest = append(cmdsToTest, "network rm")
  102. if testEnv.ExperimentalDaemon() {
  103. cmdsToTest = append(cmdsToTest, "checkpoint create")
  104. cmdsToTest = append(cmdsToTest, "checkpoint ls")
  105. cmdsToTest = append(cmdsToTest, "checkpoint rm")
  106. }
  107. // Divide the list of commands into go routines and run the func testcommand on the commands in parallel
  108. // to save runtime of test
  109. errChan := make(chan error)
  110. for index := 0; index < len(cmdsToTest); index++ {
  111. go func(index int) {
  112. errChan <- testCommand(cmdsToTest[index], newEnvs, scanForHome, home)
  113. }(index)
  114. }
  115. for index := 0; index < len(cmdsToTest); index++ {
  116. err := <-errChan
  117. if err != nil {
  118. c.Fatal(err)
  119. }
  120. }
  121. }
  122. }
  123. func (s *DockerSuite) TestHelpExitCodesHelpOutput(c *check.C) {
  124. // Test to make sure the exit code and output (stdout vs stderr) of
  125. // various good and bad cases are what we expect
  126. // docker : stdout=all, stderr=empty, rc=0
  127. out, _ := dockerCmd(c)
  128. // Be really pick
  129. c.Assert(out, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have a blank line at the end of 'docker'\n"))
  130. // docker help: stdout=all, stderr=empty, rc=0
  131. out, _ = dockerCmd(c, "help")
  132. // Be really pick
  133. c.Assert(out, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have a blank line at the end of 'docker help'\n"))
  134. // docker --help: stdout=all, stderr=empty, rc=0
  135. out, _ = dockerCmd(c, "--help")
  136. // Be really pick
  137. c.Assert(out, checker.Not(checker.HasSuffix), "\n\n", check.Commentf("Should not have a blank line at the end of 'docker --help'\n"))
  138. // docker inspect busybox: stdout=all, stderr=empty, rc=0
  139. // Just making sure stderr is empty on valid cmd
  140. out, _ = dockerCmd(c, "inspect", "busybox")
  141. // Be really pick
  142. 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"))
  143. // docker rm: stdout=empty, stderr=all, rc!=0
  144. // testing the min arg error msg
  145. icmd.RunCommand(dockerBinary, "rm").Assert(c, icmd.Expected{
  146. ExitCode: 1,
  147. Error: "exit status 1",
  148. Out: "",
  149. // Should not contain full help text but should contain info about
  150. // # of args and Usage line
  151. Err: "requires at least 1 argument",
  152. })
  153. // docker rm NoSuchContainer: stdout=empty, stderr=all, rc=0
  154. // testing to make sure no blank line on error
  155. result := icmd.RunCommand(dockerBinary, "rm", "NoSuchContainer")
  156. result.Assert(c, icmd.Expected{
  157. ExitCode: 1,
  158. Error: "exit status 1",
  159. Out: "",
  160. })
  161. // Be really picky
  162. c.Assert(len(result.Stderr()), checker.Not(checker.Equals), 0)
  163. 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"))
  164. // docker BadCmd: stdout=empty, stderr=all, rc=0
  165. icmd.RunCommand(dockerBinary, "BadCmd").Assert(c, icmd.Expected{
  166. ExitCode: 1,
  167. Error: "exit status 1",
  168. Out: "",
  169. Err: "docker: 'BadCmd' is not a docker command.\nSee 'docker --help'\n",
  170. })
  171. }
  172. func testCommand(cmd string, newEnvs []string, scanForHome bool, home string) error {
  173. args := strings.Split(cmd+" --help", " ")
  174. // Check the full usage text
  175. result := icmd.RunCmd(icmd.Cmd{
  176. Command: append([]string{dockerBinary}, args...),
  177. Env: newEnvs,
  178. })
  179. err := result.Error
  180. out := result.Stdout()
  181. stderr := result.Stderr()
  182. if len(stderr) != 0 {
  183. return fmt.Errorf("Error on %q help. non-empty stderr:%q\n", cmd, stderr)
  184. }
  185. if strings.HasSuffix(out, "\n\n") {
  186. return fmt.Errorf("Should not have blank line on %q\n", cmd)
  187. }
  188. if !strings.Contains(out, "--help") {
  189. return fmt.Errorf("All commands should mention '--help'. Command '%v' did not.\n", cmd)
  190. }
  191. if err != nil {
  192. return fmt.Errorf(out)
  193. }
  194. // Check each line for lots of stuff
  195. lines := strings.Split(out, "\n")
  196. for _, line := range lines {
  197. i := strings.Index(line, "~")
  198. if i >= 0 && i != len(line)-1 && line[i+1] != '/' {
  199. return fmt.Errorf("Help for %q should not have used ~:\n%s", cmd, line)
  200. }
  201. // Options should NOT end with a period
  202. if strings.HasPrefix(line, " -") && strings.HasSuffix(line, ".") {
  203. return fmt.Errorf("Help for %q should not end with a period: %s", cmd, line)
  204. }
  205. // Options should NOT end with a space
  206. if strings.HasSuffix(line, " ") {
  207. return fmt.Errorf("Help for %q should not end with a space: %s", cmd, line)
  208. }
  209. }
  210. // For each command make sure we generate an error
  211. // if we give a bad arg
  212. args = strings.Split(cmd+" --badArg", " ")
  213. out, _, err = dockerCmdWithError(args...)
  214. if err == nil {
  215. return fmt.Errorf(out)
  216. }
  217. // Be really picky
  218. if strings.HasSuffix(stderr, "\n\n") {
  219. return fmt.Errorf("Should not have a blank line at the end of 'docker rm'\n")
  220. }
  221. // Now make sure that each command will print a short-usage
  222. // (not a full usage - meaning no opts section) if we
  223. // are missing a required arg or pass in a bad arg
  224. // These commands will never print a short-usage so don't test
  225. noShortUsage := map[string]string{
  226. "images": "",
  227. "login": "",
  228. "logout": "",
  229. "network": "",
  230. "stats": "",
  231. "volume create": "",
  232. }
  233. if _, ok := noShortUsage[cmd]; !ok {
  234. // skipNoArgs are ones that we don't want to try w/o
  235. // any args. Either because it'll hang the test or
  236. // lead to incorrect test result (like false negative).
  237. // Whatever the reason, skip trying to run w/o args and
  238. // jump to trying with a bogus arg.
  239. skipNoArgs := map[string]struct{}{
  240. "daemon": {},
  241. "events": {},
  242. "load": {},
  243. }
  244. var result *icmd.Result
  245. if _, ok := skipNoArgs[cmd]; !ok {
  246. result = dockerCmdWithResult(strings.Split(cmd, " ")...)
  247. }
  248. // If its ok w/o any args then try again with an arg
  249. if result == nil || result.ExitCode == 0 {
  250. result = dockerCmdWithResult(strings.Split(cmd+" badArg", " ")...)
  251. }
  252. if err := result.Compare(icmd.Expected{
  253. Out: icmd.None,
  254. Err: "\nUsage:",
  255. ExitCode: 1,
  256. }); err != nil {
  257. return err
  258. }
  259. stderr := result.Stderr()
  260. // Shouldn't have full usage
  261. if strings.Contains(stderr, "--help=false") {
  262. return fmt.Errorf("Should not have full usage on %q:%v", result.Cmd.Args, stderr)
  263. }
  264. if strings.HasSuffix(stderr, "\n\n") {
  265. return fmt.Errorf("Should not have a blank line on %q\n%v", result.Cmd.Args, stderr)
  266. }
  267. }
  268. return nil
  269. }