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.7 kB

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