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

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