You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

unit_tests.go 6.1 kB

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