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

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