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 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package unittest
  5. import (
  6. "context"
  7. "fmt"
  8. "net/url"
  9. "os"
  10. "path/filepath"
  11. "testing"
  12. "code.gitea.io/gitea/models/db"
  13. "code.gitea.io/gitea/modules/base"
  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.GravatarSourceURL, err = url.Parse("https://secure.gravatar.com/avatar/")
  81. if err != nil {
  82. fatalTestError("url.Parse: %v\n", err)
  83. }
  84. setting.Attachment.Storage.Path = filepath.Join(setting.AppDataPath, "attachments")
  85. setting.LFS.Storage.Path = filepath.Join(setting.AppDataPath, "lfs")
  86. setting.Avatar.Storage.Path = filepath.Join(setting.AppDataPath, "avatars")
  87. setting.RepoAvatar.Storage.Path = filepath.Join(setting.AppDataPath, "repo-avatars")
  88. setting.RepoArchive.Storage.Path = filepath.Join(setting.AppDataPath, "repo-archive")
  89. setting.Packages.Storage.Path = filepath.Join(setting.AppDataPath, "packages")
  90. if err = storage.Init(); err != nil {
  91. fatalTestError("storage.Init: %v\n", err)
  92. }
  93. if err = util.RemoveAll(repoRootPath); err != nil {
  94. fatalTestError("util.RemoveAll: %v\n", err)
  95. }
  96. if err = CopyDir(filepath.Join(testOpts.GiteaRootPath, "integrations", "gitea-repositories-meta"), setting.RepoRootPath); err != nil {
  97. fatalTestError("util.CopyDir: %v\n", err)
  98. }
  99. ownerDirs, err := os.ReadDir(setting.RepoRootPath)
  100. if err != nil {
  101. fatalTestError("unable to read the new repo root: %v\n", err)
  102. }
  103. for _, ownerDir := range ownerDirs {
  104. if !ownerDir.Type().IsDir() {
  105. continue
  106. }
  107. repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name()))
  108. if err != nil {
  109. fatalTestError("unable to read the new repo root: %v\n", err)
  110. }
  111. for _, repoDir := range repoDirs {
  112. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
  113. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
  114. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
  115. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
  116. }
  117. }
  118. if testOpts.SetUp != nil {
  119. if err := testOpts.SetUp(); err != nil {
  120. fatalTestError("set up failed: %v\n", err)
  121. }
  122. }
  123. exitStatus := m.Run()
  124. if testOpts.TearDown != nil {
  125. if err := testOpts.TearDown(); err != nil {
  126. fatalTestError("tear down failed: %v\n", err)
  127. }
  128. }
  129. if err = util.RemoveAll(repoRootPath); err != nil {
  130. fatalTestError("util.RemoveAll: %v\n", err)
  131. }
  132. if err = util.RemoveAll(appDataPath); err != nil {
  133. fatalTestError("util.RemoveAll: %v\n", err)
  134. }
  135. os.Exit(exitStatus)
  136. }
  137. // FixturesOptions fixtures needs to be loaded options
  138. type FixturesOptions struct {
  139. Dir string
  140. Files []string
  141. }
  142. // CreateTestEngine creates a memory database and loads the fixture data from fixturesDir
  143. func CreateTestEngine(opts FixturesOptions) error {
  144. x, err := xorm.NewEngine("sqlite3", "file::memory:?cache=shared&_txlock=immediate")
  145. if err != nil {
  146. return err
  147. }
  148. x.SetMapper(names.GonicMapper{})
  149. db.SetDefaultEngine(context.Background(), x)
  150. if err = db.SyncAllTables(); err != nil {
  151. return err
  152. }
  153. switch os.Getenv("GITEA_UNIT_TESTS_LOG_SQL") {
  154. case "true", "1":
  155. x.ShowSQL(true)
  156. }
  157. return InitFixtures(opts)
  158. }
  159. // PrepareTestDatabase load test fixtures into test database
  160. func PrepareTestDatabase() error {
  161. return LoadFixtures()
  162. }
  163. // PrepareTestEnv prepares the environment for unit tests. Can only be called
  164. // by tests that use the above MainTest(..) function.
  165. func PrepareTestEnv(t testing.TB) {
  166. assert.NoError(t, PrepareTestDatabase())
  167. assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
  168. metaPath := filepath.Join(giteaRoot, "integrations", "gitea-repositories-meta")
  169. assert.NoError(t, CopyDir(metaPath, setting.RepoRootPath))
  170. ownerDirs, err := os.ReadDir(setting.RepoRootPath)
  171. assert.NoError(t, err)
  172. for _, ownerDir := range ownerDirs {
  173. if !ownerDir.Type().IsDir() {
  174. continue
  175. }
  176. repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name()))
  177. assert.NoError(t, err)
  178. for _, repoDir := range repoDirs {
  179. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
  180. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)
  181. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "heads"), 0o755)
  182. _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "tag"), 0o755)
  183. }
  184. }
  185. base.SetupGiteaRoot() // Makes sure GITEA_ROOT is set
  186. }