main_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2020 The Gogs 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 db
  5. import (
  6. "flag"
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "path/filepath"
  11. "testing"
  12. "time"
  13. "github.com/jinzhu/gorm"
  14. log "unknwon.dev/clog/v2"
  15. "gogs.io/gogs/internal/conf"
  16. "gogs.io/gogs/internal/dbutil"
  17. "gogs.io/gogs/internal/testutil"
  18. )
  19. var printSQL = flag.Bool("print-sql", false, "Print SQL executed")
  20. func TestMain(m *testing.M) {
  21. flag.Parse()
  22. if !testing.Verbose() {
  23. // Remove the primary logger and register a noop logger.
  24. log.Remove(log.DefaultConsoleName)
  25. err := log.New("noop", testutil.InitNoopLogger)
  26. if err != nil {
  27. fmt.Println(err)
  28. os.Exit(1)
  29. }
  30. }
  31. now := time.Now().Truncate(time.Second)
  32. gorm.NowFunc = func() time.Time { return now }
  33. os.Exit(m.Run())
  34. }
  35. func deleteTables(db *gorm.DB, tables ...interface{}) error {
  36. for _, t := range tables {
  37. err := db.Delete(t).Error
  38. if err != nil {
  39. return err
  40. }
  41. }
  42. return nil
  43. }
  44. func initTestDB(t *testing.T, suite string, tables ...interface{}) *gorm.DB {
  45. t.Helper()
  46. dbpath := filepath.Join(os.TempDir(), fmt.Sprintf("gogs-%s-%d.db", suite, time.Now().Unix()))
  47. db, err := openDB(conf.DatabaseOpts{
  48. Type: "sqlite3",
  49. Path: dbpath,
  50. })
  51. if err != nil {
  52. t.Fatal(err)
  53. }
  54. t.Cleanup(func() {
  55. _ = db.Close()
  56. if t.Failed() {
  57. t.Logf("Database %q left intact for inspection", dbpath)
  58. return
  59. }
  60. _ = os.Remove(dbpath)
  61. })
  62. db.SingularTable(true)
  63. if !testing.Verbose() {
  64. db.SetLogger(&dbutil.Writer{Writer: ioutil.Discard})
  65. }
  66. if *printSQL {
  67. db.LogMode(true)
  68. }
  69. err = db.AutoMigrate(tables...).Error
  70. if err != nil {
  71. t.Fatal(err)
  72. }
  73. return db
  74. }