client_hwid_schema_test.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package database
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strings"
  6. "testing"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. "gorm.io/driver/postgres"
  9. "gorm.io/gorm"
  10. "gorm.io/gorm/logger"
  11. )
  12. func assertClientHwidSchema(t *testing.T, db *gorm.DB) {
  13. t.Helper()
  14. if !db.Migrator().HasColumn(&model.ClientRecord{}, "limit_hwid") {
  15. t.Fatalf("clients.limit_hwid missing")
  16. }
  17. if !db.Migrator().HasTable(&model.ClientHwid{}) {
  18. t.Fatalf("client_hwids table missing")
  19. }
  20. for _, col := range []string{"sub_id", "hwid_hash", "first_seen", "last_seen", "user_agent", "device_os", "os_version", "device_model"} {
  21. if !db.Migrator().HasColumn(&model.ClientHwid{}, col) {
  22. t.Fatalf("client_hwids.%s missing", col)
  23. }
  24. }
  25. if !db.Migrator().HasIndex(&model.ClientHwid{}, "idx_client_hwids_sub_hash") {
  26. t.Fatalf("client_hwids unique hash index missing")
  27. }
  28. }
  29. func TestClientHwidSchemaSQLite(t *testing.T) {
  30. dbDir := t.TempDir()
  31. t.Setenv("XUI_DB_FOLDER", dbDir)
  32. if err := InitDB(filepath.Join(dbDir, "x-ui.db")); err != nil {
  33. t.Fatalf("InitDB: %v", err)
  34. }
  35. t.Cleanup(func() { _ = CloseDB() })
  36. assertClientHwidSchema(t, GetDB())
  37. }
  38. func TestClientHwidSchemaPostgres(t *testing.T) {
  39. dsn := strings.TrimSpace(os.Getenv("XUI_TEST_PG_DSN"))
  40. if dsn == "" {
  41. t.Skip("set XUI_TEST_PG_DSN to a reachable Postgres to run this test")
  42. }
  43. db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Discard})
  44. if err != nil {
  45. t.Fatalf("open postgres: %v", err)
  46. }
  47. sqlDB, err := db.DB()
  48. if err != nil {
  49. t.Fatalf("postgres db handle: %v", err)
  50. }
  51. t.Cleanup(func() { _ = sqlDB.Close() })
  52. if err := db.AutoMigrate(&model.ClientRecord{}, &model.ClientHwid{}); err != nil {
  53. t.Fatalf("automigrate postgres: %v", err)
  54. }
  55. assertClientHwidSchema(t, db)
  56. }