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

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