docker_cli_help_test.go 11 KB

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