main_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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. "os"
  9. "path/filepath"
  10. "testing"
  11. "time"
  12. "gorm.io/gorm"
  13. "gorm.io/gorm/logger"
  14. "gorm.io/gorm/schema"
  15. log "unknwon.dev/clog/v2"
  16. "gogs.io/gogs/internal/conf"
  17. "gogs.io/gogs/internal/testutil"
  18. )
  19. func TestMain(m *testing.M) {
  20. flag.Parse()
  21. level := logger.Silent
  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. } else {
  31. level = logger.Info
  32. }
  33. // NOTE: AutoMigrate does not respect logger passed in gorm.Config.
  34. logger.Default = logger.Default.LogMode(level)
  35. os.Exit(m.Run())
  36. }
  37. // clearTables removes all rows from given tables.
  38. func clearTables(t *testing.T, db *gorm.DB, tables ...interface{}) error {
  39. if t.Failed() {
  40. return nil
  41. }
  42. for _, t := range tables {
  43. err := db.Where("TRUE").Delete(t).Error
  44. if err != nil {
  45. return err
  46. }
  47. }
  48. return nil
  49. }
  50. func initTestDB(t *testing.T, suite string, tables ...interface{}) *gorm.DB {
  51. t.Helper()
  52. dbpath := filepath.Join(os.TempDir(), fmt.Sprintf("gogs-%s-%d.db", suite, time.Now().Unix()))
  53. now := time.Now().UTC().Truncate(time.Second)
  54. db, err := openDB(
  55. conf.DatabaseOpts{
  56. Type: "sqlite3",
  57. Path: dbpath,
  58. },
  59. &gorm.Config{
  60. NamingStrategy: schema.NamingStrategy{
  61. SingularTable: true,
  62. },
  63. NowFunc: func() time.Time {
  64. return now
  65. },
  66. },
  67. )
  68. if err != nil {
  69. t.Fatal(err)
  70. }
  71. t.Cleanup(func() {
  72. sqlDB, err := db.DB()
  73. if err == nil {
  74. _ = sqlDB.Close()
  75. }
  76. if t.Failed() {
  77. t.Logf("Database %q left intact for inspection", dbpath)
  78. return
  79. }
  80. _ = os.Remove(dbpath)
  81. })
  82. err = db.Migrator().AutoMigrate(tables...)
  83. if err != nil {
  84. t.Fatal(err)
  85. }
  86. return db
  87. }