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.

testdb.go 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package unittest
  4. import (
  5. "context"
  6. "fmt"
  7. "os"
  8. "path/filepath"
  9. "testing"
  10. "code.gitea.io/gitea/models/db"
  11. system_model "code.gitea.io/gitea/models/system"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/git"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/storage"
  16. "code.gitea.io/gitea/modules/util"
  17. "github.com/stretchr/testify/assert"
  18. "xorm.io/xorm"
  19. "xorm.io/xorm/names"
  20. )
  21. // giteaRoot a path to the gitea root
  22. var (
  23. giteaRoot string
  24. fixturesDir string
  25. )
  26. // FixturesDir returns the fixture directory
  27. func FixturesDir() string {
  28. return fixturesDir
  29. }
  30. func fatalTestError(fmtStr string, args ...interface{}) {
  31. _, _ = fmt.Fprintf(os.Stderr, fmtStr, args...)
  32. os.Exit(1)
  33. }
  34. // TestOptions represents test options
  35. type TestOptions struct {
  36. GiteaRootPath string
  37. FixtureFiles []string
  38. SetUp func() error // SetUp will be executed before all tests in this package
  39. TearDown func() error // TearDown will be executed after all tests in this package
  40. }
  41. // MainTest a reusable TestMain(..) function for unit tests that need to use a
  42. // test database. Creates the test database, and sets necessary settings.
  43. func MainTest(m *testing.M, testOpts *TestOptions) {
  44. var err error
  45. giteaRoot = testOpts.GiteaRootPath
  46. fixturesDir = filepath.Join(testOpts.GiteaRootPath, "models", "fixtures")
  47. var opts FixturesOptions
  48. if len(testOpts.FixtureFiles) == 0 {
  49. opts.Dir = fixturesDir
  50. } else {
  51. for _, f := range testOpts.FixtureFiles {
  52. if len(f) != 0 {
  53. opts.Files = append(opts.Files, filepath.Join(fixturesDir, f))
  54. }
  55. }
  56. }
  57. if err = CreateTestEngine(opts); err != nil {
  58. fatalTestError("Error creating test engine: %v\n", err)
  59. }
  60. setting.AppURL = "https://try.gitea.io/"
  61. setting.RunUser = "runuser"
  62. setting.SSH.User = "sshuser"
  63. setting.SSH.BuiltinServerUser = "builtinuser"
  64. setting.SSH.Port = 3000
  65. setting.SSH.Domain = "try.gitea.io"
  66. setting.Database.UseSQLite3 = true
  67. setting.Repository.DefaultBranch = "master" // many test code still assume that default branch is called "master"
  68. repoRootPath, err := os.MkdirTemp(os.TempDir(), "repos")
  69. if err != nil {
  70. fatalTestError("TempDir: %v\n", err)
  71. }
  72. setting.RepoRootPath = repoRootPath
  73. appDataPath, err := os.MkdirTemp(os.TempDir(), "appdata")
  74. if err != nil {
  75. fatalTestError("TempDir: %v\n", err)
  76. }
  77. setting.AppDataPath = appDataPath
  78. setting.AppWorkPath = testOpts.GiteaRootPath
  79. setting.StaticRootPath = testOpts.GiteaRootPath
  80. setting.GravatarSource = "https://secure.gravatar.com/avatar/"
  81. setting.Attachment.Storage.Path = filepath.Join(setting.AppDataPath, "attachments")
  82. setting.LFS.Storage.Path = filepath.Join(setting.AppDataPath, "lfs")
  83. setting.Avatar.Storage.Path = filepath.Join(setting.AppDataPath, "avatars")
  84. setting.RepoAvatar.Storage.Path = filepath.Join(setting.AppDataPath, "repo-avatars")
  85. setting.RepoArchive.Storage.Path = filepath.Join(setting.AppDataPath, "repo-archive")
  86. setting.Packages.Storage.Path = filepath.Join(setting.AppDataPath, "packages")
  87. setting.Actions.Storage.Path = filepath.Join(setting.AppDataPath, "actions_log")
  88. setting.Git.HomePath = filepath.Join(setting.AppDataPath, "home")
  89. setting.IncomingEmail.ReplyToAddress = "incoming+%{token}@localhost"
  90. if err = storage.Init(); err != nil {
  91. fatalTestError("storage.Init: %v\n", err)
  92. }
  93. if err = system_model.Init(); err != nil {
  94. fatalTestError("models.Init: %v\n", err)
  95. }
  96. if err = util.RemoveAll(repoRootPath); err != nil {
  97. fatalTestError("util.RemoveAll: %v\n", err)
  98. }
  99. if err = CopyDir(filepath.Join(testOpts.GiteaRootPath, "tests", "gitea-repositories-meta"), setting.RepoRootPath); err != nil {
  100. fatalTestError("util.CopyDir: %v\n", err)
  101. }
  102. if err = git.InitFull(context.Background()); err != nil {
  103. fatalTestError("git.Init: %v\n", err)
  104. }
  105. ownerDirs, err := os.ReadDir(setting.RepoRootPath)
  106. if err != nil {
  107. fatalTestError("unable to read the new repo root: %v\n", err)
  108. }
  109. for _, ownerDir := range ownerDirs {
  110. if !ownerDir.Type().IsDir() {
  111. continue
  112. }
  113. repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name()))
  114. if err != nil {
  115. fatalTestError("unable to read the new repo root: %v\n", err)
  116. }
  117. for _, repoDir := range repoDirs {
  118. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
  119. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
  120. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
  121. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
  122. }
  123. }
  124. if testOpts.SetUp != nil {
  125. if err := testOpts.SetUp(); err != nil {
  126. fatalTestError("set up failed: %v\n", err)
  127. }
  128. }
  129. exitStatus := m.Run()
  130. if testOpts.TearDown != nil {
  131. if err := testOpts.TearDown(); err != nil {
  132. fatalTestError("tear down failed: %v\n", err)
  133. }
  134. }
  135. if err = util.RemoveAll(repoRootPath); err != nil {
  136. fatalTestError("util.RemoveAll: %v\n", err)
  137. }
  138. if err = util.RemoveAll(appDataPath); err != nil {
  139. fatalTestError("util.RemoveAll: %v\n", err)
  140. }
  141. os.Exit(exitStatus)
  142. }
  143. // FixturesOptions fixtures needs to be loaded options
  144. type FixturesOptions struct {
  145. Dir string
  146. Files []string
  147. }
  148. // CreateTestEngine creates a memory database and loads the fixture data from fixturesDir
  149. func CreateTestEngine(opts FixturesOptions) error {
  150. x, err := xorm.NewEngine("sqlite3", "file::memory:?cache=shared&_txlock=immediate")
  151. if err != nil {
  152. return err
  153. }
  154. x.SetMapper(names.GonicMapper{})
  155. db.SetDefaultEngine(context.Background(), x)
  156. if err = db.SyncAllTables(); err != nil {
  157. return err
  158. }
  159. switch os.Getenv("GITEA_UNIT_TESTS_LOG_SQL") {
  160. case "true", "1":
  161. x.ShowSQL(true)
  162. }
  163. return InitFixtures(opts)
  164. }
  165. // PrepareTestDatabase load test fixtures into test database
  166. func PrepareTestDatabase() error {
  167. return LoadFixtures()
  168. }
  169. // PrepareTestEnv prepares the environment for unit tests. Can only be called
  170. // by tests that use the above MainTest(..) function.
  171. func PrepareTestEnv(t testing.TB) {
  172. assert.NoError(t, PrepareTestDatabase())
  173. assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
  174. metaPath := filepath.Join(giteaRoot, "tests", "gitea-repositories-meta")
  175. assert.NoError(t, CopyDir(metaPath, setting.RepoRootPath))
  176. ownerDirs, err := os.ReadDir(setting.RepoRootPath)
  177. assert.NoError(t, err)
  178. for _, ownerDir := range ownerDirs {
  179. if !ownerDir.Type().IsDir() {
  180. continue
  181. }
  182. repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name()))
  183. assert.NoError(t, err)
  184. for _, repoDir := range repoDirs {
  185. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
  186. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
  187. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
  188. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
  189. }
  190. }
  191. base.SetupGiteaRoot() // Makes sure GITEA_ROOT is set
  192. }