1
0

db_seed_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package database
  2. import (
  3. "encoding/json"
  4. "path/filepath"
  5. "testing"
  6. "github.com/mhsanaei/3x-ui/v3/database/model"
  7. )
  8. func TestSeedClientsFromInboundJSON_IsIdempotentAgainstExistingClients(t *testing.T) {
  9. dbDir := t.TempDir()
  10. t.Setenv("XUI_DB_FOLDER", dbDir)
  11. if err := InitDB(filepath.Join(dbDir, "3x-ui.db")); err != nil {
  12. t.Fatalf("InitDB failed: %v", err)
  13. }
  14. t.Cleanup(func() { _ = CloseDB() })
  15. settings, err := json.Marshal(map[string]any{
  16. "clients": []any{
  17. map[string]any{
  18. "id": "ce8d33df-3a64-4f10-8f9b-91c3a8e0c001",
  19. "email": "[email protected]",
  20. "enable": true,
  21. "flow": "",
  22. "subId": "alice-sub",
  23. "comment": "from-inbound-json",
  24. },
  25. },
  26. })
  27. if err != nil {
  28. t.Fatalf("marshal settings: %v", err)
  29. }
  30. inbound := model.Inbound{
  31. UserId: 1,
  32. Port: 12345,
  33. Protocol: model.VLESS,
  34. Settings: string(settings),
  35. Tag: "test-inbound",
  36. }
  37. if err := db.Create(&inbound).Error; err != nil {
  38. t.Fatalf("seed inbound: %v", err)
  39. }
  40. preExisting := &model.ClientRecord{
  41. Email: "[email protected]",
  42. UUID: "ce8d33df-3a64-4f10-8f9b-91c3a8e0c001",
  43. SubID: "alice-sub",
  44. Enable: true,
  45. Comment: "added-via-api",
  46. }
  47. if err := db.Create(preExisting).Error; err != nil {
  48. t.Fatalf("seed client row: %v", err)
  49. }
  50. if err := db.Where("seeder_name = ?", "ClientsTable").Delete(&model.HistoryOfSeeders{}).Error; err != nil {
  51. t.Fatalf("clear ClientsTable history: %v", err)
  52. }
  53. if err := seedClientsFromInboundJSON(); err != nil {
  54. t.Fatalf("seedClientsFromInboundJSON should be idempotent against existing rows, got: %v", err)
  55. }
  56. var count int64
  57. if err := db.Model(&model.ClientRecord{}).Where("email = ?", "[email protected]").Count(&count).Error; err != nil {
  58. t.Fatalf("count clients: %v", err)
  59. }
  60. if count != 1 {
  61. t.Fatalf("[email protected] should resolve to exactly one row, got %d", count)
  62. }
  63. }