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.

unit_tests.go 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. // Copyright 2016 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 db
  5. import (
  6. "context"
  7. "fmt"
  8. "math"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "testing"
  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. // NonexistentID an ID that will never exist
  22. const NonexistentID = int64(math.MaxInt64)
  23. // giteaRoot a path to the gitea root
  24. var (
  25. giteaRoot string
  26. fixturesDir string
  27. )
  28. // FixturesDir returns the fixture directory
  29. func FixturesDir() string {
  30. return fixturesDir
  31. }
  32. func fatalTestError(fmtStr string, args ...interface{}) {
  33. fmt.Fprintf(os.Stderr, fmtStr, args...)
  34. os.Exit(1)
  35. }
  36. // MainTest a reusable TestMain(..) function for unit tests that need to use a
  37. // test database. Creates the test database, and sets necessary settings.
  38. func MainTest(m *testing.M, pathToGiteaRoot string, fixtureFiles ...string) {
  39. var err error
  40. giteaRoot = pathToGiteaRoot
  41. fixturesDir = filepath.Join(pathToGiteaRoot, "models", "fixtures")
  42. var opts FixturesOptions
  43. if len(fixtureFiles) == 0 {
  44. opts.Dir = fixturesDir
  45. } else {
  46. for _, f := range fixtureFiles {
  47. if len(f) != 0 {
  48. opts.Files = append(opts.Files, filepath.Join(fixturesDir, f))
  49. }
  50. }
  51. }
  52. if err = CreateTestEngine(opts); err != nil {
  53. fatalTestError("Error creating test engine: %v\n", err)
  54. }
  55. setting.AppURL = "https://try.gitea.io/"
  56. setting.RunUser = "runuser"
  57. setting.SSH.Port = 3000
  58. setting.SSH.Domain = "try.gitea.io"
  59. setting.Database.UseSQLite3 = true
  60. setting.RepoRootPath, err = os.MkdirTemp(os.TempDir(), "repos")
  61. if err != nil {
  62. fatalTestError("TempDir: %v\n", err)
  63. }
  64. setting.AppDataPath, err = os.MkdirTemp(os.TempDir(), "appdata")
  65. if err != nil {
  66. fatalTestError("TempDir: %v\n", err)
  67. }
  68. setting.AppWorkPath = pathToGiteaRoot
  69. setting.StaticRootPath = pathToGiteaRoot
  70. setting.GravatarSourceURL, err = url.Parse("https://secure.gravatar.com/avatar/")
  71. if err != nil {
  72. fatalTestError("url.Parse: %v\n", err)
  73. }
  74. setting.Attachment.Storage.Path = filepath.Join(setting.AppDataPath, "attachments")
  75. setting.LFS.Storage.Path = filepath.Join(setting.AppDataPath, "lfs")
  76. setting.Avatar.Storage.Path = filepath.Join(setting.AppDataPath, "avatars")
  77. setting.RepoAvatar.Storage.Path = filepath.Join(setting.AppDataPath, "repo-avatars")
  78. setting.RepoArchive.Storage.Path = filepath.Join(setting.AppDataPath, "repo-archive")
  79. if err = storage.Init(); err != nil {
  80. fatalTestError("storage.Init: %v\n", err)
  81. }
  82. if err = util.RemoveAll(setting.RepoRootPath); err != nil {
  83. fatalTestError("util.RemoveAll: %v\n", err)
  84. }
  85. if err = util.CopyDir(filepath.Join(pathToGiteaRoot, "integrations", "gitea-repositories-meta"), setting.RepoRootPath); err != nil {
  86. fatalTestError("util.CopyDir: %v\n", err)
  87. }
  88. exitStatus := m.Run()
  89. if err = util.RemoveAll(setting.RepoRootPath); err != nil {
  90. fatalTestError("util.RemoveAll: %v\n", err)
  91. }
  92. if err = util.RemoveAll(setting.AppDataPath); err != nil {
  93. fatalTestError("util.RemoveAll: %v\n", err)
  94. }
  95. os.Exit(exitStatus)
  96. }
  97. // FixturesOptions fixtures needs to be loaded options
  98. type FixturesOptions struct {
  99. Dir string
  100. Files []string
  101. }
  102. // CreateTestEngine creates a memory database and loads the fixture data from fixturesDir
  103. func CreateTestEngine(opts FixturesOptions) error {
  104. var err error
  105. x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared&_txlock=immediate")
  106. if err != nil {
  107. return err
  108. }
  109. x.SetMapper(names.GonicMapper{})
  110. if err = syncTables(); err != nil {
  111. return err
  112. }
  113. switch os.Getenv("GITEA_UNIT_TESTS_VERBOSE") {
  114. case "true", "1":
  115. x.ShowSQL(true)
  116. }
  117. DefaultContext = &Context{
  118. Context: context.Background(),
  119. e: x,
  120. }
  121. return InitFixtures(opts)
  122. }
  123. // PrepareTestDatabase load test fixtures into test database
  124. func PrepareTestDatabase() error {
  125. return LoadFixtures()
  126. }
  127. // PrepareTestEnv prepares the environment for unit tests. Can only be called
  128. // by tests that use the above MainTest(..) function.
  129. func PrepareTestEnv(t testing.TB) {
  130. assert.NoError(t, PrepareTestDatabase())
  131. assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
  132. metaPath := filepath.Join(giteaRoot, "integrations", "gitea-repositories-meta")
  133. assert.NoError(t, util.CopyDir(metaPath, setting.RepoRootPath))
  134. base.SetupGiteaRoot() // Makes sure GITEA_ROOT is set
  135. }
  136. type testCond struct {
  137. query interface{}
  138. args []interface{}
  139. }
  140. // Cond create a condition with arguments for a test
  141. func Cond(query interface{}, args ...interface{}) interface{} {
  142. return &testCond{query: query, args: args}
  143. }
  144. func whereConditions(sess *xorm.Session, conditions []interface{}) {
  145. for _, condition := range conditions {
  146. switch cond := condition.(type) {
  147. case *testCond:
  148. sess.Where(cond.query, cond.args...)
  149. default:
  150. sess.Where(cond)
  151. }
  152. }
  153. }
  154. // LoadBeanIfExists loads beans from fixture database if exist
  155. func LoadBeanIfExists(bean interface{}, conditions ...interface{}) (bool, error) {
  156. return loadBeanIfExists(bean, conditions...)
  157. }
  158. func loadBeanIfExists(bean interface{}, conditions ...interface{}) (bool, error) {
  159. sess := x.NewSession()
  160. defer sess.Close()
  161. whereConditions(sess, conditions)
  162. return sess.Get(bean)
  163. }
  164. // BeanExists for testing, check if a bean exists
  165. func BeanExists(t testing.TB, bean interface{}, conditions ...interface{}) bool {
  166. exists, err := loadBeanIfExists(bean, conditions...)
  167. assert.NoError(t, err)
  168. return exists
  169. }
  170. // AssertExistsAndLoadBean assert that a bean exists and load it from the test
  171. // database
  172. func AssertExistsAndLoadBean(t testing.TB, bean interface{}, conditions ...interface{}) interface{} {
  173. exists, err := loadBeanIfExists(bean, conditions...)
  174. assert.NoError(t, err)
  175. assert.True(t, exists,
  176. "Expected to find %+v (of type %T, with conditions %+v), but did not",
  177. bean, bean, conditions)
  178. return bean
  179. }
  180. // GetCount get the count of a bean
  181. func GetCount(t testing.TB, bean interface{}, conditions ...interface{}) int {
  182. sess := x.NewSession()
  183. defer sess.Close()
  184. whereConditions(sess, conditions)
  185. count, err := sess.Count(bean)
  186. assert.NoError(t, err)
  187. return int(count)
  188. }
  189. // AssertNotExistsBean assert that a bean does not exist in the test database
  190. func AssertNotExistsBean(t testing.TB, bean interface{}, conditions ...interface{}) {
  191. exists, err := loadBeanIfExists(bean, conditions...)
  192. assert.NoError(t, err)
  193. assert.False(t, exists)
  194. }
  195. // AssertExistsIf asserts that a bean exists or does not exist, depending on
  196. // what is expected.
  197. func AssertExistsIf(t *testing.T, expected bool, bean interface{}, conditions ...interface{}) {
  198. exists, err := loadBeanIfExists(bean, conditions...)
  199. assert.NoError(t, err)
  200. assert.Equal(t, expected, exists)
  201. }
  202. // AssertSuccessfulInsert assert that beans is successfully inserted
  203. func AssertSuccessfulInsert(t testing.TB, beans ...interface{}) {
  204. _, err := x.Insert(beans...)
  205. assert.NoError(t, err)
  206. }
  207. // AssertCount assert the count of a bean
  208. func AssertCount(t testing.TB, bean, expected interface{}) {
  209. assert.EqualValues(t, expected, GetCount(t, bean))
  210. }
  211. // AssertInt64InRange assert value is in range [low, high]
  212. func AssertInt64InRange(t testing.TB, low, high, value int64) {
  213. assert.True(t, value >= low && value <= high,
  214. "Expected value in range [%d, %d], found %d", low, high, value)
  215. }