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

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