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.

setup_for_test.go 2.2 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. "testing"
  9. "github.com/go-xorm/core"
  10. "github.com/go-xorm/xorm"
  11. _ "github.com/mattn/go-sqlite3" // for the test engine
  12. "github.com/stretchr/testify/assert"
  13. "gopkg.in/testfixtures.v2"
  14. )
  15. const NonexistentID = 9223372036854775807
  16. func TestMain(m *testing.M) {
  17. if err := CreateTestEngine(); err != nil {
  18. fmt.Printf("Error creating test engine: %v\n", err)
  19. os.Exit(1)
  20. }
  21. os.Exit(m.Run())
  22. }
  23. var fixtures *testfixtures.Context
  24. // CreateTestEngine create an xorm engine for testing
  25. func CreateTestEngine() error {
  26. testfixtures.SkipDatabaseNameCheck(true)
  27. var err error
  28. x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared")
  29. if err != nil {
  30. return err
  31. }
  32. x.SetMapper(core.GonicMapper{})
  33. if err = x.StoreEngine("InnoDB").Sync2(tables...); err != nil {
  34. return err
  35. }
  36. fixtures, err = testfixtures.NewFolder(x.DB().DB, &testfixtures.SQLite{}, "fixtures/")
  37. return err
  38. }
  39. // PrepareTestDatabase load test fixtures into test database
  40. func PrepareTestDatabase() error {
  41. return fixtures.Load()
  42. }
  43. func loadBeanIfExists(bean interface{}, conditions ...interface{}) (bool, error) {
  44. sess := x.NewSession()
  45. defer sess.Close()
  46. for _, cond := range conditions {
  47. sess = sess.Where(cond)
  48. }
  49. return sess.Get(bean)
  50. }
  51. // BeanExists for testing, check if a bean exists
  52. func BeanExists(t *testing.T, bean interface{}, conditions ...interface{}) bool {
  53. exists, err := loadBeanIfExists(bean, conditions...)
  54. assert.NoError(t, err)
  55. return exists
  56. }
  57. // AssertExistsAndLoadBean assert that a bean exists and load it from the test
  58. // database
  59. func AssertExistsAndLoadBean(t *testing.T, bean interface{}, conditions ...interface{}) interface{} {
  60. exists, err := loadBeanIfExists(bean, conditions...)
  61. assert.NoError(t, err)
  62. assert.True(t, exists)
  63. return bean
  64. }
  65. // AssertNotExistsBean assert that a bean does not exist in the test database
  66. func AssertNotExistsBean(t *testing.T, bean interface{}, conditions ...interface{}) {
  67. exists, err := loadBeanIfExists(bean, conditions...)
  68. assert.NoError(t, err)
  69. assert.False(t, exists)
  70. }