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.

207 lines
5.8 KiB

  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 models
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "math"
  9. "net/url"
  10. "os"
  11. "path/filepath"
  12. "testing"
  13. "time"
  14. "code.gitea.io/gitea/modules/setting"
  15. "github.com/Unknwon/com"
  16. "github.com/go-xorm/core"
  17. "github.com/go-xorm/xorm"
  18. "github.com/stretchr/testify/assert"
  19. "gopkg.in/testfixtures.v2"
  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 giteaRoot string
  25. func fatalTestError(fmtStr string, args ...interface{}) {
  26. fmt.Fprintf(os.Stderr, fmtStr, args...)
  27. os.Exit(1)
  28. }
  29. // MainTest a reusable TestMain(..) function for unit tests that need to use a
  30. // test database. Creates the test database, and sets necessary settings.
  31. func MainTest(m *testing.M, pathToGiteaRoot string) {
  32. var err error
  33. giteaRoot = pathToGiteaRoot
  34. fixturesDir := filepath.Join(pathToGiteaRoot, "models", "fixtures")
  35. if err = createTestEngine(fixturesDir); err != nil {
  36. fatalTestError("Error creating test engine: %v\n", err)
  37. }
  38. setting.AppURL = "https://try.gitea.io/"
  39. setting.RunUser = "runuser"
  40. setting.SSH.Port = 3000
  41. setting.SSH.Domain = "try.gitea.io"
  42. setting.UseSQLite3 = true
  43. setting.RepoRootPath, err = ioutil.TempDir(os.TempDir(), "repos")
  44. if err != nil {
  45. fatalTestError("TempDir: %v\n", err)
  46. }
  47. setting.AppDataPath, err = ioutil.TempDir(os.TempDir(), "appdata")
  48. if err != nil {
  49. fatalTestError("TempDir: %v\n", err)
  50. }
  51. setting.AppWorkPath = pathToGiteaRoot
  52. setting.StaticRootPath = pathToGiteaRoot
  53. setting.GravatarSourceURL, err = url.Parse("https://secure.gravatar.com/avatar/")
  54. if err != nil {
  55. fatalTestError("url.Parse: %v\n", err)
  56. }
  57. exitStatus := m.Run()
  58. if err = removeAllWithRetry(setting.RepoRootPath); err != nil {
  59. fatalTestError("os.RemoveAll: %v\n", err)
  60. }
  61. if err = removeAllWithRetry(setting.AppDataPath); err != nil {
  62. fatalTestError("os.RemoveAll: %v\n", err)
  63. }
  64. os.Exit(exitStatus)
  65. }
  66. func createTestEngine(fixturesDir string) error {
  67. var err error
  68. x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared")
  69. if err != nil {
  70. return err
  71. }
  72. x.SetMapper(core.GonicMapper{})
  73. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  74. return err
  75. }
  76. switch os.Getenv("GITEA_UNIT_TESTS_VERBOSE") {
  77. case "true", "1":
  78. x.ShowSQL(true)
  79. }
  80. return InitFixtures(&testfixtures.SQLite{}, fixturesDir)
  81. }
  82. func removeAllWithRetry(dir string) error {
  83. var err error
  84. for i := 0; i < 20; i++ {
  85. err = os.RemoveAll(dir)
  86. if err == nil {
  87. break
  88. }
  89. time.Sleep(100 * time.Millisecond)
  90. }
  91. return err
  92. }
  93. // PrepareTestDatabase load test fixtures into test database
  94. func PrepareTestDatabase() error {
  95. return LoadFixtures()
  96. }
  97. // PrepareTestEnv prepares the environment for unit tests. Can only be called
  98. // by tests that use the above MainTest(..) function.
  99. func PrepareTestEnv(t testing.TB) {
  100. assert.NoError(t, PrepareTestDatabase())
  101. assert.NoError(t, removeAllWithRetry(setting.RepoRootPath))
  102. metaPath := filepath.Join(giteaRoot, "integrations", "gitea-repositories-meta")
  103. assert.NoError(t, com.CopyDir(metaPath, setting.RepoRootPath))
  104. }
  105. type testCond struct {
  106. query interface{}
  107. args []interface{}
  108. }
  109. // Cond create a condition with arguments for a test
  110. func Cond(query interface{}, args ...interface{}) interface{} {
  111. return &testCond{query: query, args: args}
  112. }
  113. func whereConditions(sess *xorm.Session, conditions []interface{}) {
  114. for _, condition := range conditions {
  115. switch cond := condition.(type) {
  116. case *testCond:
  117. sess.Where(cond.query, cond.args...)
  118. default:
  119. sess.Where(cond)
  120. }
  121. }
  122. }
  123. func loadBeanIfExists(bean interface{}, conditions ...interface{}) (bool, error) {
  124. sess := x.NewSession()
  125. defer sess.Close()
  126. whereConditions(sess, conditions)
  127. return sess.Get(bean)
  128. }
  129. // BeanExists for testing, check if a bean exists
  130. func BeanExists(t testing.TB, bean interface{}, conditions ...interface{}) bool {
  131. exists, err := loadBeanIfExists(bean, conditions...)
  132. assert.NoError(t, err)
  133. return exists
  134. }
  135. // AssertExistsAndLoadBean assert that a bean exists and load it from the test
  136. // database
  137. func AssertExistsAndLoadBean(t testing.TB, bean interface{}, conditions ...interface{}) interface{} {
  138. exists, err := loadBeanIfExists(bean, conditions...)
  139. assert.NoError(t, err)
  140. assert.True(t, exists,
  141. "Expected to find %+v (of type %T, with conditions %+v), but did not",
  142. bean, bean, conditions)
  143. return bean
  144. }
  145. // GetCount get the count of a bean
  146. func GetCount(t testing.TB, bean interface{}, conditions ...interface{}) int {
  147. sess := x.NewSession()
  148. defer sess.Close()
  149. whereConditions(sess, conditions)
  150. count, err := sess.Count(bean)
  151. assert.NoError(t, err)
  152. return int(count)
  153. }
  154. // AssertNotExistsBean assert that a bean does not exist in the test database
  155. func AssertNotExistsBean(t testing.TB, bean interface{}, conditions ...interface{}) {
  156. exists, err := loadBeanIfExists(bean, conditions...)
  157. assert.NoError(t, err)
  158. assert.False(t, exists)
  159. }
  160. // AssertExistsIf asserts that a bean exists or does not exist, depending on
  161. // what is expected.
  162. func AssertExistsIf(t *testing.T, expected bool, bean interface{}, conditions ...interface{}) {
  163. exists, err := loadBeanIfExists(bean, conditions...)
  164. assert.NoError(t, err)
  165. assert.Equal(t, expected, exists)
  166. }
  167. // AssertSuccessfulInsert assert that beans is successfully inserted
  168. func AssertSuccessfulInsert(t testing.TB, beans ...interface{}) {
  169. _, err := x.Insert(beans...)
  170. assert.NoError(t, err)
  171. }
  172. // AssertCount assert the count of a bean
  173. func AssertCount(t testing.TB, bean interface{}, expected interface{}) {
  174. assert.EqualValues(t, expected, GetCount(t, bean))
  175. }
  176. // AssertInt64InRange assert value is in range [low, high]
  177. func AssertInt64InRange(t testing.TB, low, high, value int64) {
  178. assert.True(t, value >= low && value <= high,
  179. "Expected value in range [%d, %d], found %d", low, high, value)
  180. }