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.5 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. // LoadFixture load a test fixture from the test database, failing if fixture
  43. // does not exist
  44. func LoadTestFixture(t *testing.T, fixture interface{}, conditions... interface{}) {
  45. sess := x.NewSession()
  46. defer sess.Close()
  47. for _, cond := range conditions {
  48. sess = sess.Where(cond)
  49. }
  50. has, err := sess.Get(fixture)
  51. assert.NoError(t, err)
  52. assert.True(t, has)
  53. }