github.com/EagleQL/Xray-core@v1.4.3/app/stats/command/command_test.go (about) 1 package command_test 2 3 import ( 4 "context" 5 "testing" 6 7 "github.com/google/go-cmp/cmp" 8 "github.com/google/go-cmp/cmp/cmpopts" 9 10 "github.com/xtls/xray-core/app/stats" 11 . "github.com/xtls/xray-core/app/stats/command" 12 "github.com/xtls/xray-core/common" 13 ) 14 15 func TestGetStats(t *testing.T) { 16 m, err := stats.NewManager(context.Background(), &stats.Config{}) 17 common.Must(err) 18 19 sc, err := m.RegisterCounter("test_counter") 20 common.Must(err) 21 22 sc.Set(1) 23 24 s := NewStatsServer(m) 25 26 testCases := []struct { 27 name string 28 reset bool 29 value int64 30 err bool 31 }{ 32 { 33 name: "counterNotExist", 34 err: true, 35 }, 36 { 37 name: "test_counter", 38 reset: true, 39 value: 1, 40 }, 41 { 42 name: "test_counter", 43 value: 0, 44 }, 45 } 46 for _, tc := range testCases { 47 resp, err := s.GetStats(context.Background(), &GetStatsRequest{ 48 Name: tc.name, 49 Reset_: tc.reset, 50 }) 51 if tc.err { 52 if err == nil { 53 t.Error("nil error: ", tc.name) 54 } 55 } else { 56 common.Must(err) 57 if r := cmp.Diff(resp.Stat, &Stat{Name: tc.name, Value: tc.value}, cmpopts.IgnoreUnexported(Stat{})); r != "" { 58 t.Error(r) 59 } 60 } 61 } 62 } 63 64 func TestQueryStats(t *testing.T) { 65 m, err := stats.NewManager(context.Background(), &stats.Config{}) 66 common.Must(err) 67 68 sc1, err := m.RegisterCounter("test_counter") 69 common.Must(err) 70 sc1.Set(1) 71 72 sc2, err := m.RegisterCounter("test_counter_2") 73 common.Must(err) 74 sc2.Set(2) 75 76 sc3, err := m.RegisterCounter("test_counter_3") 77 common.Must(err) 78 sc3.Set(3) 79 80 s := NewStatsServer(m) 81 resp, err := s.QueryStats(context.Background(), &QueryStatsRequest{ 82 Pattern: "counter_", 83 }) 84 common.Must(err) 85 if r := cmp.Diff(resp.Stat, []*Stat{ 86 {Name: "test_counter_2", Value: 2}, 87 {Name: "test_counter_3", Value: 3}, 88 }, cmpopts.SortSlices(func(s1, s2 *Stat) bool { return s1.Name < s2.Name }), 89 cmpopts.IgnoreUnexported(Stat{})); r != "" { 90 t.Error(r) 91 } 92 }