You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main_test.go 5.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cmd
  4. import (
  5. "fmt"
  6. "io"
  7. "os"
  8. "path/filepath"
  9. "strings"
  10. "testing"
  11. "code.gitea.io/gitea/models/unittest"
  12. "code.gitea.io/gitea/modules/setting"
  13. "code.gitea.io/gitea/modules/test"
  14. "github.com/stretchr/testify/assert"
  15. "github.com/urfave/cli/v2"
  16. )
  17. func TestMain(m *testing.M) {
  18. unittest.MainTest(m, &unittest.TestOptions{
  19. GiteaRootPath: "..",
  20. })
  21. }
  22. func makePathOutput(workPath, customPath, customConf string) string {
  23. return fmt.Sprintf("WorkPath=%s\nCustomPath=%s\nCustomConf=%s", workPath, customPath, customConf)
  24. }
  25. func newTestApp(testCmdAction func(ctx *cli.Context) error) *cli.App {
  26. app := NewMainApp("version", "version-extra")
  27. testCmd := &cli.Command{Name: "test-cmd", Action: testCmdAction}
  28. prepareSubcommandWithConfig(testCmd, appGlobalFlags())
  29. app.Commands = append(app.Commands, testCmd)
  30. app.DefaultCommand = testCmd.Name
  31. return app
  32. }
  33. type runResult struct {
  34. Stdout string
  35. Stderr string
  36. ExitCode int
  37. }
  38. func runTestApp(app *cli.App, args ...string) (runResult, error) {
  39. outBuf := new(strings.Builder)
  40. errBuf := new(strings.Builder)
  41. app.Writer = outBuf
  42. app.ErrWriter = errBuf
  43. exitCode := -1
  44. defer test.MockVariableValue(&cli.ErrWriter, app.ErrWriter)()
  45. defer test.MockVariableValue(&cli.OsExiter, func(code int) {
  46. if exitCode == -1 {
  47. exitCode = code // save the exit code once and then reset the writer (to simulate the exit)
  48. app.Writer, app.ErrWriter, cli.ErrWriter = io.Discard, io.Discard, io.Discard
  49. }
  50. })()
  51. err := RunMainApp(app, args...)
  52. return runResult{outBuf.String(), errBuf.String(), exitCode}, err
  53. }
  54. func TestCliCmd(t *testing.T) {
  55. defaultWorkPath := filepath.Dir(setting.AppPath)
  56. defaultCustomPath := filepath.Join(defaultWorkPath, "custom")
  57. defaultCustomConf := filepath.Join(defaultCustomPath, "conf/app.ini")
  58. cli.CommandHelpTemplate = "(command help template)"
  59. cli.AppHelpTemplate = "(app help template)"
  60. cli.SubcommandHelpTemplate = "(subcommand help template)"
  61. cases := []struct {
  62. env map[string]string
  63. cmd string
  64. exp string
  65. }{
  66. // main command help
  67. {
  68. cmd: "./gitea help",
  69. exp: "DEFAULT CONFIGURATION:",
  70. },
  71. // parse paths
  72. {
  73. cmd: "./gitea test-cmd",
  74. exp: makePathOutput(defaultWorkPath, defaultCustomPath, defaultCustomConf),
  75. },
  76. {
  77. cmd: "./gitea -c /tmp/app.ini test-cmd",
  78. exp: makePathOutput(defaultWorkPath, defaultCustomPath, "/tmp/app.ini"),
  79. },
  80. {
  81. cmd: "./gitea test-cmd -c /tmp/app.ini",
  82. exp: makePathOutput(defaultWorkPath, defaultCustomPath, "/tmp/app.ini"),
  83. },
  84. {
  85. env: map[string]string{"GITEA_WORK_DIR": "/tmp"},
  86. cmd: "./gitea test-cmd",
  87. exp: makePathOutput("/tmp", "/tmp/custom", "/tmp/custom/conf/app.ini"),
  88. },
  89. {
  90. env: map[string]string{"GITEA_WORK_DIR": "/tmp"},
  91. cmd: "./gitea test-cmd --work-path /tmp/other",
  92. exp: makePathOutput("/tmp/other", "/tmp/other/custom", "/tmp/other/custom/conf/app.ini"),
  93. },
  94. {
  95. env: map[string]string{"GITEA_WORK_DIR": "/tmp"},
  96. cmd: "./gitea test-cmd --config /tmp/app-other.ini",
  97. exp: makePathOutput("/tmp", "/tmp/custom", "/tmp/app-other.ini"),
  98. },
  99. }
  100. app := newTestApp(func(ctx *cli.Context) error {
  101. _, _ = fmt.Fprint(ctx.App.Writer, makePathOutput(setting.AppWorkPath, setting.CustomPath, setting.CustomConf))
  102. return nil
  103. })
  104. var envBackup []string
  105. for _, s := range os.Environ() {
  106. if strings.HasPrefix(s, "GITEA_") && strings.Contains(s, "=") {
  107. envBackup = append(envBackup, s)
  108. }
  109. }
  110. clearGiteaEnv := func() {
  111. for _, s := range os.Environ() {
  112. if strings.HasPrefix(s, "GITEA_") {
  113. _ = os.Unsetenv(s)
  114. }
  115. }
  116. }
  117. defer func() {
  118. clearGiteaEnv()
  119. for _, s := range envBackup {
  120. k, v, _ := strings.Cut(s, "=")
  121. _ = os.Setenv(k, v)
  122. }
  123. }()
  124. for _, c := range cases {
  125. clearGiteaEnv()
  126. for k, v := range c.env {
  127. _ = os.Setenv(k, v)
  128. }
  129. args := strings.Split(c.cmd, " ") // for test only, "split" is good enough
  130. r, err := runTestApp(app, args...)
  131. assert.NoError(t, err, c.cmd)
  132. assert.NotEmpty(t, c.exp, c.cmd)
  133. assert.Contains(t, r.Stdout, c.exp, c.cmd)
  134. }
  135. }
  136. func TestCliCmdError(t *testing.T) {
  137. app := newTestApp(func(ctx *cli.Context) error { return fmt.Errorf("normal error") })
  138. r, err := runTestApp(app, "./gitea", "test-cmd")
  139. assert.Error(t, err)
  140. assert.Equal(t, 1, r.ExitCode)
  141. assert.Equal(t, "", r.Stdout)
  142. assert.Equal(t, "Command error: normal error\n", r.Stderr)
  143. app = newTestApp(func(ctx *cli.Context) error { return cli.Exit("exit error", 2) })
  144. r, err = runTestApp(app, "./gitea", "test-cmd")
  145. assert.Error(t, err)
  146. assert.Equal(t, 2, r.ExitCode)
  147. assert.Equal(t, "", r.Stdout)
  148. assert.Equal(t, "exit error\n", r.Stderr)
  149. app = newTestApp(func(ctx *cli.Context) error { return nil })
  150. r, err = runTestApp(app, "./gitea", "test-cmd", "--no-such")
  151. assert.Error(t, err)
  152. assert.Equal(t, 1, r.ExitCode)
  153. assert.Equal(t, "Incorrect Usage: flag provided but not defined: -no-such\n\n", r.Stdout)
  154. assert.Equal(t, "", r.Stderr) // the cli package's strange behavior, the error message is not in stderr ....
  155. app = newTestApp(func(ctx *cli.Context) error { return nil })
  156. r, err = runTestApp(app, "./gitea", "test-cmd")
  157. assert.NoError(t, err)
  158. assert.Equal(t, -1, r.ExitCode) // the cli.OsExiter is not called
  159. assert.Equal(t, "", r.Stdout)
  160. assert.Equal(t, "", r.Stderr)
  161. }