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

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