You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

97 lines
2.3 KiB

  1. package trust
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestTrustMetricScores(t *testing.T) {
  8. tm := NewMetric()
  9. tm.Start()
  10. // Perfect score
  11. tm.GoodEvents(1)
  12. score := tm.TrustScore()
  13. assert.Equal(t, 100, score)
  14. // Less than perfect score
  15. tm.BadEvents(10)
  16. score = tm.TrustScore()
  17. assert.NotEqual(t, 100, score)
  18. tm.Stop()
  19. }
  20. func TestTrustMetricConfig(t *testing.T) {
  21. // 7 days
  22. window := time.Minute * 60 * 24 * 7
  23. config := TrustMetricConfig{
  24. TrackingWindow: window,
  25. IntervalLength: 2 * time.Minute,
  26. }
  27. tm := NewMetricWithConfig(config)
  28. tm.Start()
  29. // The max time intervals should be the TrackingWindow / IntervalLen
  30. assert.Equal(t, int(config.TrackingWindow/config.IntervalLength), tm.maxIntervals)
  31. dc := DefaultConfig()
  32. // These weights should still be the default values
  33. assert.Equal(t, dc.ProportionalWeight, tm.proportionalWeight)
  34. assert.Equal(t, dc.IntegralWeight, tm.integralWeight)
  35. tm.Stop()
  36. tm.Wait()
  37. config.ProportionalWeight = 0.3
  38. config.IntegralWeight = 0.7
  39. tm = NewMetricWithConfig(config)
  40. tm.Start()
  41. // These weights should be equal to our custom values
  42. assert.Equal(t, config.ProportionalWeight, tm.proportionalWeight)
  43. assert.Equal(t, config.IntegralWeight, tm.integralWeight)
  44. tm.Stop()
  45. tm.Wait()
  46. }
  47. func TestTrustMetricStopPause(t *testing.T) {
  48. // The TestTicker will provide manual control over
  49. // the passing of time within the metric
  50. tt := NewTestTicker()
  51. tm := NewMetric()
  52. tm.SetTicker(tt)
  53. tm.Start()
  54. // Allow some time intervals to pass and pause
  55. tt.NextTick()
  56. tt.NextTick()
  57. tm.Pause()
  58. // could be 1 or 2 because Pause and NextTick race
  59. first := tm.Copy().numIntervals
  60. // Allow more time to pass and check the intervals are unchanged
  61. tt.NextTick()
  62. tt.NextTick()
  63. assert.Equal(t, first, tm.Copy().numIntervals)
  64. // Get the trust metric activated again
  65. tm.GoodEvents(5)
  66. // Allow some time intervals to pass and stop
  67. tt.NextTick()
  68. tt.NextTick()
  69. tm.Stop()
  70. tm.Wait()
  71. second := tm.Copy().numIntervals
  72. // Allow more intervals to pass while the metric is stopped
  73. // and check that the number of intervals match
  74. tm.NextTimeInterval()
  75. tm.NextTimeInterval()
  76. assert.Equal(t, second+2, tm.Copy().numIntervals)
  77. if first > second {
  78. t.Fatalf("numIntervals should always increase or stay the same over time")
  79. }
  80. }