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.8KB

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