1
0

client_lookup_test.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package service
  2. import (
  3. "testing"
  4. "github.com/mhsanaei/3x-ui/v3/internal/database"
  5. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  6. )
  7. func TestGetRecordsByTgID(t *testing.T) {
  8. setupBulkDB(t)
  9. svc := &ClientService{}
  10. db := database.GetDB()
  11. records := []model.ClientRecord{
  12. {Email: "alice@x", TgID: 100, SubID: "sa"},
  13. {Email: "bob@x", TgID: 100, SubID: "sb"},
  14. {Email: "carol@x", TgID: 200, SubID: "sc"},
  15. {Email: "dave@x", TgID: 0, SubID: "sd"},
  16. }
  17. for _, r := range records {
  18. if err := db.Create(&r).Error; err != nil {
  19. t.Fatalf("create record %q: %v", r.Email, err)
  20. }
  21. }
  22. t.Run("multiple clients share tgId", func(t *testing.T) {
  23. got, err := svc.GetRecordsByTgID(100)
  24. if err != nil {
  25. t.Fatalf("GetRecordsByTgID(100): %v", err)
  26. }
  27. if len(got) != 2 {
  28. t.Fatalf("expected 2 records, got %d", len(got))
  29. }
  30. emails := make(map[string]bool)
  31. for _, r := range got {
  32. emails[r.Email] = true
  33. }
  34. if !emails["alice@x"] || !emails["bob@x"] {
  35. t.Fatalf("expected alice@x and bob@x, got %v", got)
  36. }
  37. })
  38. t.Run("single client by tgId", func(t *testing.T) {
  39. got, err := svc.GetRecordsByTgID(200)
  40. if err != nil {
  41. t.Fatalf("GetRecordsByTgID(200): %v", err)
  42. }
  43. if len(got) != 1 {
  44. t.Fatalf("expected 1 record, got %d", len(got))
  45. }
  46. if got[0].Email != "carol@x" {
  47. t.Fatalf("expected carol@x, got %s", got[0].Email)
  48. }
  49. })
  50. t.Run("tgId zero rejected as sentinel", func(t *testing.T) {
  51. _, err := svc.GetRecordsByTgID(0)
  52. if err == nil {
  53. t.Fatal("expected error for tgId=0")
  54. }
  55. })
  56. t.Run("negative tgId rejected", func(t *testing.T) {
  57. _, err := svc.GetRecordsByTgID(-5)
  58. if err == nil {
  59. t.Fatal("expected error for tgId=-5")
  60. }
  61. })
  62. t.Run("nonexistent tgId returns empty", func(t *testing.T) {
  63. got, err := svc.GetRecordsByTgID(999)
  64. if err != nil {
  65. t.Fatalf("GetRecordsByTgID(999): %v", err)
  66. }
  67. if len(got) != 0 {
  68. t.Fatalf("expected 0 records, got %d", len(got))
  69. }
  70. })
  71. }