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.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. // 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. time.Sleep(50 * time.Millisecond)
  51. tm.Pause()
  52. // Give the pause some time to take place
  53. time.Sleep(10 * time.Millisecond)
  54. first := tm.Copy().numIntervals
  55. // Allow more time to pass and check the intervals are unchanged
  56. time.Sleep(50 * time.Millisecond)
  57. assert.Equal(t, first, tm.numIntervals)
  58. // Get the trust metric activated again
  59. tm.GoodEvents(5)
  60. // Allow some time intervals to pass and stop
  61. time.Sleep(50 * time.Millisecond)
  62. tm.Stop()
  63. // Give the stop some time to take place
  64. time.Sleep(10 * time.Millisecond)
  65. second := tm.Copy().numIntervals
  66. // Allow more time to pass and check the intervals are unchanged
  67. time.Sleep(50 * time.Millisecond)
  68. assert.Equal(t, second, tm.numIntervals)
  69. if first >= second {
  70. t.Fatalf("numIntervals should always increase or stay the same over time")
  71. }
  72. }