mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-09-29 02:32:07 +03:00
12d51d7195
Most tests opened a throwaway panel DB with database.InitDB, which runs the full AutoMigrate + seed on an empty file every time: ~230ms, and ~850ms under -race because GORM's reflection-heavy migration is what the detector slows most. internal/web/service does this in ~550 of its 830 tests, so the CI race job spent ~10 of its ~14.6 minutes re-migrating empty databases. internal/database/dbtest.InitDB migrates once per test process, then hands each test its own copy of that file (~130ms under -race) and registers the CloseDB cleanup. The copy then goes through InitDB like a panel restart, so every test still starts from the state a fresh install has. Tests that reopen an existing file, migrate a hand-built legacy DB or target Postgres keep calling database.InitDB. Locally under -race: internal/web/service 626s (last CI run) -> 114s, internal/sub 246s -> 35s.
53 lines
1.7 KiB
Go
53 lines
1.7 KiB
Go
package sub
|
|
|
|
import (
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database/dbtest"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
|
"github.com/mhsanaei/3x-ui/v3/internal/xray"
|
|
)
|
|
|
|
// statsForClient recovers a client's usage by email when the client_traffics row
|
|
// is orphaned — its inbound_id points at an inbound that was deleted and
|
|
// recreated, so the preloaded ClientStats and the statsByEmail index both miss.
|
|
// Before the email fallback, {{TRAFFIC_USED}} stayed at 0 for such pre-existing
|
|
// clients while the sub-info header was correct (#5567).
|
|
func TestStatsForClient_OrphanedInboundIdFallback(t *testing.T) {
|
|
dbDir := t.TempDir()
|
|
t.Setenv("XUI_DB_FOLDER", dbDir)
|
|
dbtest.InitDB(t, filepath.Join(dbDir, "x-ui.db"))
|
|
|
|
const email = "old-client@example.com"
|
|
const total = int64(100) * gb
|
|
|
|
db := database.GetDB()
|
|
if err := db.Create(&xray.ClientTraffic{
|
|
InboundId: 999,
|
|
Email: email,
|
|
Up: 15 * gb,
|
|
Down: 5 * gb,
|
|
Total: total,
|
|
Enable: true,
|
|
}).Error; err != nil {
|
|
t.Fatalf("seed orphaned traffic: %v", err)
|
|
}
|
|
|
|
s := &SubService{statsByEmail: map[string]xray.ClientTraffic{}}
|
|
inbound := &model.Inbound{Id: 1, Remark: "DE"}
|
|
client := model.Client{Email: email, TotalGB: total, Enable: true}
|
|
|
|
st := s.statsForClient(inbound, client)
|
|
if used := st.Up + st.Down; used != 20*gb {
|
|
t.Fatalf("statsForClient used = %d, want %d (email fallback)", used, 20*gb)
|
|
}
|
|
if _, ok := s.statsByEmail[email]; !ok {
|
|
t.Fatalf("email fallback must cache the row into statsByEmail")
|
|
}
|
|
if got := remarkVarValue("TRAFFIC_USED", remarkContext{stats: st}); got != "20.00GB" {
|
|
t.Fatalf("TRAFFIC_USED = %q, want 20.00GB", got)
|
|
}
|
|
}
|