unstable_test.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package mathx
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func TestUnstable_AroundDuration(t *testing.T) {
  8. unstable := NewUnstable(0.05)
  9. for i := 0; i < 1000; i++ {
  10. val := unstable.AroundDuration(time.Second)
  11. assert.True(t, float64(time.Second)*0.95 <= float64(val))
  12. assert.True(t, float64(val) <= float64(time.Second)*1.05)
  13. }
  14. }
  15. func TestUnstable_AroundInt(t *testing.T) {
  16. const target = 10000
  17. unstable := NewUnstable(0.05)
  18. for i := 0; i < 1000; i++ {
  19. val := unstable.AroundInt(target)
  20. assert.True(t, float64(target)*0.95 <= float64(val))
  21. assert.True(t, float64(val) <= float64(target)*1.05)
  22. }
  23. }
  24. func TestUnstable_AroundIntLarge(t *testing.T) {
  25. const target int64 = 10000
  26. unstable := NewUnstable(5)
  27. for i := 0; i < 1000; i++ {
  28. val := unstable.AroundInt(target)
  29. assert.True(t, 0 <= val)
  30. assert.True(t, val <= 2*target)
  31. }
  32. }
  33. func TestUnstable_AroundIntNegative(t *testing.T) {
  34. const target int64 = 10000
  35. unstable := NewUnstable(-0.05)
  36. for i := 0; i < 1000; i++ {
  37. val := unstable.AroundInt(target)
  38. assert.Equal(t, target, val)
  39. }
  40. }
  41. func TestUnstable_Distribution(t *testing.T) {
  42. const (
  43. seconds = 10000
  44. total = 10000
  45. )
  46. m := make(map[int]int)
  47. expiry := NewUnstable(0.05)
  48. for i := 0; i < total; i++ {
  49. val := int(expiry.AroundInt(seconds))
  50. m[val]++
  51. }
  52. _, ok := m[0]
  53. assert.False(t, ok)
  54. mi := make(map[interface{}]int, len(m))
  55. for k, v := range m {
  56. mi[k] = v
  57. }
  58. entropy := CalcEntropy(mi)
  59. assert.True(t, len(m) > 1)
  60. assert.True(t, entropy > 0.95)
  61. }