main_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. // clearTables removes all rows from given tables.
  36. func clearTables(db *gorm.DB, tables ...interface{}) error {
  37. for _, t := range tables {
  38. err := db.Delete(t).Error
  39. if err != nil {
  40. return err
  41. }
  42. }
  43. return nil
  44. }
  45. func initTestDB(t *testing.T, suite string, tables ...interface{}) *gorm.DB {
  46. t.Helper()
  47. dbpath := filepath.Join(os.TempDir(), fmt.Sprintf("gogs-%s-%d.db", suite, time.Now().Unix()))
  48. db, err := openDB(conf.DatabaseOpts{
  49. Type: "sqlite3",
  50. Path: dbpath,
  51. })
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. t.Cleanup(func() {
  56. _ = db.Close()
  57. if t.Failed() {
  58. t.Logf("Database %q left intact for inspection", dbpath)
  59. return
  60. }
  61. _ = os.Remove(dbpath)
  62. })
  63. db.SingularTable(true)
  64. if !testing.Verbose() {
  65. db.SetLogger(&dbutil.Writer{Writer: ioutil.Discard})
  66. }
  67. if *printSQL {
  68. db.LogMode(true)
  69. }
  70. err = db.AutoMigrate(tables...).Error
  71. if err != nil {
  72. t.Fatal(err)
  73. }
  74. return db
  75. }