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

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