1
0

service_orphaned_stats_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package sub
  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. // statsForClient recovers a client's usage by email when the client_traffics row
  11. // is orphaned — its inbound_id points at an inbound that was deleted and
  12. // recreated, so the preloaded ClientStats and the statsByEmail index both miss.
  13. // Before the email fallback, {{TRAFFIC_USED}} stayed at 0 for such pre-existing
  14. // clients while the sub-info header was correct (#5567).
  15. func TestStatsForClient_OrphanedInboundIdFallback(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. const email = "[email protected]"
  20. const total = int64(100) * gb
  21. db := database.GetDB()
  22. if err := db.Create(&xray.ClientTraffic{
  23. InboundId: 999,
  24. Email: email,
  25. Up: 15 * gb,
  26. Down: 5 * gb,
  27. Total: total,
  28. Enable: true,
  29. }).Error; err != nil {
  30. t.Fatalf("seed orphaned traffic: %v", err)
  31. }
  32. s := &SubService{statsByEmail: map[string]xray.ClientTraffic{}}
  33. inbound := &model.Inbound{Id: 1, Remark: "DE"}
  34. client := model.Client{Email: email, TotalGB: total, Enable: true}
  35. st := s.statsForClient(inbound, client)
  36. if used := st.Up + st.Down; used != 20*gb {
  37. t.Fatalf("statsForClient used = %d, want %d (email fallback)", used, 20*gb)
  38. }
  39. if _, ok := s.statsByEmail[email]; !ok {
  40. t.Fatalf("email fallback must cache the row into statsByEmail")
  41. }
  42. if got := remarkVarValue("TRAFFIC_USED", remarkContext{stats: st}); got != "20.00GB" {
  43. t.Fatalf("TRAFFIC_USED = %q, want 20.00GB", got)
  44. }
  45. }