command_test.go 1.8 KB

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