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

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