inbound_tgbot_lookup_test.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package service
  2. import (
  3. "path/filepath"
  4. "testing"
  5. "github.com/mhsanaei/3x-ui/v3/internal/database"
  6. "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
  7. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  8. "github.com/mhsanaei/3x-ui/v3/internal/xray"
  9. )
  10. // TestGetClientTrafficTgBot_SettingsSerializationStyles guards against the
  11. // prefilter regressing into a formatting-sensitive string match (#5805): the
  12. // lookup must find clients whether inbounds.settings stores compact JSON
  13. // ("tgId":N, as written by node sync/import) or indented JSON ("tgId": N, as
  14. // written by the panel's MarshalIndent).
  15. func TestGetClientTrafficTgBot_SettingsSerializationStyles(t *testing.T) {
  16. dbDir := t.TempDir()
  17. t.Setenv("XUI_DB_FOLDER", dbDir)
  18. dbtest.InitDB(t, filepath.Join(dbDir, "x-ui.db"))
  19. db := database.GetDB()
  20. const tgId int64 = 123456789
  21. cases := []struct {
  22. name string
  23. settings string
  24. email string
  25. port int
  26. }{
  27. {"compact", `{"clients":[{"id":"u1","email":"compact-user","tgId":123456789}]}`, "compact-user", 41001},
  28. {"spaced", `{"clients": [{"id": "u2", "email": "spaced-user", "tgId": 123456789}]}`, "spaced-user", 41002},
  29. }
  30. for _, c := range cases {
  31. inbound := &model.Inbound{UserId: 1, Tag: "tg-" + c.name, Enable: true, Port: c.port, Protocol: model.VLESS, Settings: c.settings}
  32. if err := db.Create(inbound).Error; err != nil {
  33. t.Fatalf("create %s inbound: %v", c.name, err)
  34. }
  35. if err := db.Create(&xray.ClientTraffic{InboundId: inbound.Id, Email: c.email, Enable: true, Up: 10, Down: 20}).Error; err != nil {
  36. t.Fatalf("create %s client_traffics: %v", c.name, err)
  37. }
  38. }
  39. svc := InboundService{}
  40. traffics, err := svc.GetClientTrafficTgBot(tgId)
  41. if err != nil {
  42. t.Fatalf("GetClientTrafficTgBot: %v", err)
  43. }
  44. got := make(map[string]bool, len(traffics))
  45. for _, tr := range traffics {
  46. got[tr.Email] = true
  47. }
  48. if len(traffics) != 2 || !got["compact-user"] || !got["spaced-user"] {
  49. t.Fatalf("expected traffic for compact-user and spaced-user, got %v", got)
  50. }
  51. other, err := svc.GetClientTrafficTgBot(42)
  52. if err != nil {
  53. t.Fatalf("GetClientTrafficTgBot(42): %v", err)
  54. }
  55. if len(other) != 0 {
  56. t.Fatalf("expected no traffic for unknown tgId, got %d rows", len(other))
  57. }
  58. }