main_test.go 1.8 KB

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