main_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. "testing"
  10. "gorm.io/gorm"
  11. "gorm.io/gorm/logger"
  12. _ "modernc.org/sqlite"
  13. log "unknwon.dev/clog/v2"
  14. "gogs.io/gogs/internal/conf"
  15. "gogs.io/gogs/internal/testutil"
  16. )
  17. func TestMain(m *testing.M) {
  18. flag.Parse()
  19. level := logger.Silent
  20. if !testing.Verbose() {
  21. // Remove the primary logger and register a noop logger.
  22. log.Remove(log.DefaultConsoleName)
  23. err := log.New("noop", testutil.InitNoopLogger)
  24. if err != nil {
  25. fmt.Println(err)
  26. os.Exit(1)
  27. }
  28. } else {
  29. level = logger.Info
  30. }
  31. // NOTE: AutoMigrate does not respect logger passed in gorm.Config.
  32. logger.Default = logger.Default.LogMode(level)
  33. switch os.Getenv("GOGS_DATABASE_TYPE") {
  34. case "mysql":
  35. conf.UseMySQL = true
  36. case "postgres":
  37. conf.UsePostgreSQL = true
  38. default:
  39. conf.UseSQLite3 = true
  40. }
  41. os.Exit(m.Run())
  42. }
  43. // clearTables removes all rows from given tables.
  44. func clearTables(t *testing.T, db *gorm.DB, tables ...any) error {
  45. if t.Failed() {
  46. return nil
  47. }
  48. for _, t := range tables {
  49. err := db.Where("TRUE").Delete(t).Error
  50. if err != nil {
  51. return err
  52. }
  53. }
  54. return nil
  55. }