github.com/xtls/xray-core@v1.8.12-0.20240518155711-3168d27b0bdb/app/observatory/burst/healthping_result_test.go (about) 1 package burst_test 2 3 import ( 4 "math" 5 reflect "reflect" 6 "testing" 7 "time" 8 9 "github.com/xtls/xray-core/app/observatory/burst" 10 ) 11 12 func TestHealthPingResults(t *testing.T) { 13 rtts := []int64{60, 140, 60, 140, 60, 60, 140, 60, 140} 14 hr := burst.NewHealthPingResult(4, time.Hour) 15 for _, rtt := range rtts { 16 hr.Put(time.Duration(rtt)) 17 } 18 rttFailed := time.Duration(math.MaxInt64) 19 expected := &burst.HealthPingStats{ 20 All: 4, 21 Fail: 0, 22 Deviation: 40, 23 Average: 100, 24 Max: 140, 25 Min: 60, 26 } 27 actual := hr.Get() 28 if !reflect.DeepEqual(expected, actual) { 29 t.Errorf("expected: %v, actual: %v", expected, actual) 30 } 31 hr.Put(rttFailed) 32 hr.Put(rttFailed) 33 expected.Fail = 2 34 actual = hr.Get() 35 if !reflect.DeepEqual(expected, actual) { 36 t.Errorf("failed half-failures test, expected: %v, actual: %v", expected, actual) 37 } 38 hr.Put(rttFailed) 39 hr.Put(rttFailed) 40 expected = &burst.HealthPingStats{ 41 All: 4, 42 Fail: 4, 43 Deviation: 0, 44 Average: 0, 45 Max: 0, 46 Min: 0, 47 } 48 actual = hr.Get() 49 if !reflect.DeepEqual(expected, actual) { 50 t.Errorf("failed all-failures test, expected: %v, actual: %v", expected, actual) 51 } 52 } 53 54 func TestHealthPingResultsIgnoreOutdated(t *testing.T) { 55 rtts := []int64{60, 140, 60, 140} 56 hr := burst.NewHealthPingResult(4, time.Duration(10)*time.Millisecond) 57 for i, rtt := range rtts { 58 if i == 2 { 59 // wait for previous 2 outdated 60 time.Sleep(time.Duration(10) * time.Millisecond) 61 } 62 hr.Put(time.Duration(rtt)) 63 } 64 hr.Get() 65 expected := &burst.HealthPingStats{ 66 All: 2, 67 Fail: 0, 68 Deviation: 40, 69 Average: 100, 70 Max: 140, 71 Min: 60, 72 } 73 actual := hr.Get() 74 if !reflect.DeepEqual(expected, actual) { 75 t.Errorf("failed 'half-outdated' test, expected: %v, actual: %v", expected, actual) 76 } 77 // wait for all outdated 78 time.Sleep(time.Duration(10) * time.Millisecond) 79 expected = &burst.HealthPingStats{ 80 All: 0, 81 Fail: 0, 82 Deviation: 0, 83 Average: 0, 84 Max: 0, 85 Min: 0, 86 } 87 actual = hr.Get() 88 if !reflect.DeepEqual(expected, actual) { 89 t.Errorf("failed 'outdated / not-tested' test, expected: %v, actual: %v", expected, actual) 90 } 91 92 hr.Put(time.Duration(60)) 93 expected = &burst.HealthPingStats{ 94 All: 1, 95 Fail: 0, 96 // 1 sample, std=0.5rtt 97 Deviation: 30, 98 Average: 60, 99 Max: 60, 100 Min: 60, 101 } 102 actual = hr.Get() 103 if !reflect.DeepEqual(expected, actual) { 104 t.Errorf("expected: %v, actual: %v", expected, actual) 105 } 106 }