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.

90 lines
2.2 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. // Perfect score
  10. tm.GoodEvents(1)
  11. score := tm.TrustScore()
  12. assert.Equal(t, 100, score)
  13. // Less than perfect score
  14. tm.BadEvents(10)
  15. score = tm.TrustScore()
  16. assert.NotEqual(t, 100, score)
  17. tm.Stop()
  18. }
  19. func TestTrustMetricConfig(t *testing.T) {
  20. // 7 days
  21. window := time.Minute * 60 * 24 * 7
  22. config := TrustMetricConfig{
  23. TrackingWindow: window,
  24. IntervalLength: 2 * time.Minute,
  25. }
  26. tm := NewMetricWithConfig(config)
  27. // The max time intervals should be the TrackingWindow / IntervalLen
  28. assert.Equal(t, int(config.TrackingWindow/config.IntervalLength), tm.maxIntervals)
  29. dc := DefaultConfig()
  30. // These weights should still be the default values
  31. assert.Equal(t, dc.ProportionalWeight, tm.proportionalWeight)
  32. assert.Equal(t, dc.IntegralWeight, tm.integralWeight)
  33. tm.Stop()
  34. config.ProportionalWeight = 0.3
  35. config.IntegralWeight = 0.7
  36. tm = NewMetricWithConfig(config)
  37. // These weights should be equal to our custom values
  38. assert.Equal(t, config.ProportionalWeight, tm.proportionalWeight)
  39. assert.Equal(t, config.IntegralWeight, tm.integralWeight)
  40. tm.Stop()
  41. }
  42. func TestTrustMetricStopPause(t *testing.T) {
  43. // Cause time intervals to pass quickly
  44. config := TrustMetricConfig{
  45. TrackingWindow: 5 * time.Minute,
  46. IntervalLength: 10 * time.Millisecond,
  47. }
  48. tm := NewMetricWithConfig(config)
  49. // Allow some time intervals to pass and pause
  50. tm.NextTimeInterval()
  51. tm.NextTimeInterval()
  52. tm.Pause()
  53. first := tm.Copy().numIntervals
  54. // Allow more time to pass and check the intervals are unchanged
  55. tm.WaitForTimeIntervalToPass()
  56. tm.WaitForTimeIntervalToPass()
  57. assert.Equal(t, first, tm.Copy().numIntervals)
  58. // Get the trust metric activated again
  59. tm.GoodEvents(5)
  60. // Allow some time intervals to pass and stop
  61. tm.NextTimeInterval()
  62. tm.NextTimeInterval()
  63. tm.Stop()
  64. second := tm.Copy().numIntervals
  65. // Allow more intervals to pass and check that the number of intervals match
  66. tm.NextTimeInterval()
  67. tm.NextTimeInterval()
  68. assert.Equal(t, second+2, tm.Copy().numIntervals)
  69. if first > second {
  70. t.Fatalf("numIntervals should always increase or stay the same over time")
  71. }
  72. }