setup_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package exchange_test
  2. import (
  3. "fmt"
  4. "os"
  5. "testing"
  6. "time"
  7. "gorm.io/driver/sqlite"
  8. "gorm.io/gorm"
  9. "gorm.io/gorm/logger"
  10. )
  11. var (
  12. db *gorm.DB
  13. )
  14. var tables = []interface{}{
  15. &TestExchangeModel{},
  16. &TestExchangeCompositePrimaryKeyModel{},
  17. &Phone{},
  18. &Intro{},
  19. &ExtraIntro{},
  20. &Camera{},
  21. &ShoppingSite{},
  22. }
  23. type TestExchangeModel struct {
  24. ID uint `gorm:"primarykey"`
  25. Name string
  26. Age *int
  27. Birth *time.Time
  28. Appender string
  29. }
  30. type TestExchangeCompositePrimaryKeyModel struct {
  31. ID uint `gorm:"primarykey"`
  32. Name string `gorm:"primarykey"`
  33. Age *int
  34. Appender string
  35. }
  36. func TestMain(m *testing.M) {
  37. var err error
  38. db, err = gorm.Open(sqlite.Open("/tmp/test_exchange.db"), &gorm.Config{
  39. DisableForeignKeyConstraintWhenMigrating: true,
  40. })
  41. if err != nil {
  42. panic(err)
  43. }
  44. db.Logger = db.Logger.LogMode(logger.Info)
  45. migrateTables()
  46. s := m.Run()
  47. // dropTables()
  48. os.Exit(s)
  49. }
  50. func migrateTables() {
  51. if err := db.AutoMigrate(tables...); err != nil {
  52. panic(err)
  53. }
  54. }
  55. func dropTables() {
  56. var err error
  57. for _, m := range tables {
  58. stmt := &gorm.Statement{DB: db}
  59. stmt.Parse(m)
  60. err = db.Exec(fmt.Sprintf("drop table %s", stmt.Schema.Table)).Error
  61. if err != nil {
  62. panic(err)
  63. }
  64. }
  65. err = db.Exec(fmt.Sprintf("drop table phone_selling_shopping_site")).Error
  66. if err != nil {
  67. panic(err)
  68. }
  69. }
  70. func initTables() {
  71. dropTables()
  72. migrateTables()
  73. }
  74. func ptrInt(v int) *int {
  75. return &v
  76. }
  77. func ptrTime(v time.Time) *time.Time {
  78. return &v
  79. }