github.com/okex/exchain@v1.8.0/libs/tendermint/p2p/trust/metric_test.go (about) 1 package trust 2 3 import ( 4 "testing" 5 "time" 6 7 "github.com/stretchr/testify/assert" 8 ) 9 10 func TestTrustMetricScores(t *testing.T) { 11 tm := NewMetric() 12 tm.Start() 13 14 // Perfect score 15 tm.GoodEvents(1) 16 score := tm.TrustScore() 17 assert.Equal(t, 100, score) 18 19 // Less than perfect score 20 tm.BadEvents(10) 21 score = tm.TrustScore() 22 assert.NotEqual(t, 100, score) 23 tm.Stop() 24 } 25 26 func TestTrustMetricConfig(t *testing.T) { 27 // 7 days 28 window := time.Minute * 60 * 24 * 7 29 config := MetricConfig{ 30 TrackingWindow: window, 31 IntervalLength: 2 * time.Minute, 32 } 33 34 tm := NewMetricWithConfig(config) 35 tm.Start() 36 37 // The max time intervals should be the TrackingWindow / IntervalLen 38 assert.Equal(t, int(config.TrackingWindow/config.IntervalLength), tm.maxIntervals) 39 40 dc := DefaultConfig() 41 // These weights should still be the default values 42 assert.Equal(t, dc.ProportionalWeight, tm.proportionalWeight) 43 assert.Equal(t, dc.IntegralWeight, tm.integralWeight) 44 tm.Stop() 45 tm.Wait() 46 47 config.ProportionalWeight = 0.3 48 config.IntegralWeight = 0.7 49 tm = NewMetricWithConfig(config) 50 tm.Start() 51 52 // These weights should be equal to our custom values 53 assert.Equal(t, config.ProportionalWeight, tm.proportionalWeight) 54 assert.Equal(t, config.IntegralWeight, tm.integralWeight) 55 tm.Stop() 56 tm.Wait() 57 } 58 59 func TestTrustMetricCopyNilPointer(t *testing.T) { 60 var tm *Metric 61 62 ctm := tm.Copy() 63 64 assert.Nil(t, ctm) 65 } 66 67 // XXX: This test fails non-deterministically 68 //nolint:unused,deadcode 69 func _TestTrustMetricStopPause(t *testing.T) { 70 // The TestTicker will provide manual control over 71 // the passing of time within the metric 72 tt := NewTestTicker() 73 tm := NewMetric() 74 tm.SetTicker(tt) 75 tm.Start() 76 // Allow some time intervals to pass and pause 77 tt.NextTick() 78 tt.NextTick() 79 tm.Pause() 80 81 // could be 1 or 2 because Pause and NextTick race 82 first := tm.Copy().numIntervals 83 84 // Allow more time to pass and check the intervals are unchanged 85 tt.NextTick() 86 tt.NextTick() 87 assert.Equal(t, first, tm.Copy().numIntervals) 88 89 // Get the trust metric activated again 90 tm.GoodEvents(5) 91 // Allow some time intervals to pass and stop 92 tt.NextTick() 93 tt.NextTick() 94 tm.Stop() 95 tm.Wait() 96 97 second := tm.Copy().numIntervals 98 // Allow more intervals to pass while the metric is stopped 99 // and check that the number of intervals match 100 tm.NextTimeInterval() 101 tm.NextTimeInterval() 102 // XXX: fails non-deterministically: 103 // expected 5, got 6 104 assert.Equal(t, second+2, tm.Copy().numIntervals) 105 106 if first > second { 107 t.Fatalf("numIntervals should always increase or stay the same over time") 108 } 109 }