scale_helpers_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package service
  2. import (
  3. "os"
  4. "path/filepath"
  5. "strings"
  6. "testing"
  7. "github.com/mhsanaei/3x-ui/v3/internal/config"
  8. "github.com/mhsanaei/3x-ui/v3/internal/database"
  9. xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger"
  10. "github.com/op/go-logging"
  11. "gorm.io/gorm"
  12. )
  13. // setupScaleDB initializes the DB for a scale benchmark on either Postgres
  14. // (XUI_DB_TYPE=postgres + XUI_DB_DSN) or SQLite (XUI_SCALE_TEST=1, temp file),
  15. // and registers cleanup. Skips the test when neither backend is configured.
  16. func setupScaleDB(t *testing.T) {
  17. t.Helper()
  18. xuilogger.InitLogger(logging.ERROR)
  19. if os.Getenv("XUI_DB_TYPE") == "postgres" && strings.TrimSpace(os.Getenv("XUI_DB_DSN")) != "" {
  20. if err := database.InitDB(""); err != nil {
  21. t.Fatalf("InitDB(postgres): %v", err)
  22. }
  23. t.Cleanup(func() { _ = database.CloseDB() })
  24. return
  25. }
  26. switch strings.ToLower(strings.TrimSpace(os.Getenv("XUI_SCALE_TEST"))) {
  27. case "1", "true", "yes":
  28. dbPath := filepath.Join(t.TempDir(), "scale.db")
  29. if err := database.InitDB(dbPath); err != nil {
  30. t.Fatalf("InitDB(sqlite): %v", err)
  31. }
  32. t.Cleanup(func() { _ = database.CloseDB() })
  33. return
  34. }
  35. t.Skip("set XUI_SCALE_TEST=1 (sqlite) or XUI_DB_TYPE=postgres + XUI_DB_DSN (postgres) to run the scale benchmark")
  36. }
  37. // resetScaleTables empties the given tables between sub-sizes. Postgres uses a
  38. // single TRUNCATE ... CASCADE; SQLite deletes per table and clears the
  39. // autoincrement counters so ids restart like RESTART IDENTITY.
  40. func resetScaleTables(t *testing.T, db *gorm.DB, tables ...string) {
  41. t.Helper()
  42. if config.GetDBKind() == "postgres" {
  43. stmt := "TRUNCATE TABLE " + strings.Join(tables, ", ") + " RESTART IDENTITY CASCADE"
  44. if err := db.Exec(stmt).Error; err != nil {
  45. t.Fatalf("truncate: %v", err)
  46. }
  47. return
  48. }
  49. for _, tbl := range tables {
  50. if err := db.Exec("DELETE FROM " + tbl).Error; err != nil {
  51. t.Fatalf("delete %s: %v", tbl, err)
  52. }
  53. }
  54. // Best-effort id reset; sqlite_sequence is absent until the first insert.
  55. db.Exec("DELETE FROM sqlite_sequence")
  56. }