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.

73 lines
1.6 KiB

  1. package p2p
  2. import (
  3. "math"
  4. "math/rand"
  5. "net"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/require"
  9. )
  10. func randByte() byte {
  11. return byte(rand.Intn(math.MaxUint8))
  12. }
  13. func randLocalIPv4() net.IP {
  14. return net.IPv4(127, randByte(), randByte(), randByte())
  15. }
  16. func TestConnTracker(t *testing.T) {
  17. for name, factory := range map[string]func() connectionTracker{
  18. "BaseSmall": func() connectionTracker {
  19. return newConnTracker(10, time.Second)
  20. },
  21. "BaseLarge": func() connectionTracker {
  22. return newConnTracker(100, time.Hour)
  23. },
  24. } {
  25. t.Run(name, func(t *testing.T) {
  26. factory := factory // nolint:scopelint
  27. t.Run("Initialized", func(t *testing.T) {
  28. ct := factory()
  29. require.Equal(t, 0, ct.Len())
  30. })
  31. t.Run("RepeatedAdding", func(t *testing.T) {
  32. ct := factory()
  33. ip := randLocalIPv4()
  34. require.NoError(t, ct.AddConn(ip))
  35. for i := 0; i < 100; i++ {
  36. _ = ct.AddConn(ip)
  37. }
  38. require.Equal(t, 1, ct.Len())
  39. })
  40. t.Run("AddingMany", func(t *testing.T) {
  41. ct := factory()
  42. for i := 0; i < 100; i++ {
  43. _ = ct.AddConn(randLocalIPv4())
  44. }
  45. require.Equal(t, 100, ct.Len())
  46. })
  47. t.Run("Cycle", func(t *testing.T) {
  48. ct := factory()
  49. for i := 0; i < 100; i++ {
  50. ip := randLocalIPv4()
  51. require.NoError(t, ct.AddConn(ip))
  52. ct.RemoveConn(ip)
  53. }
  54. require.Equal(t, 0, ct.Len())
  55. })
  56. })
  57. }
  58. t.Run("VeryShort", func(t *testing.T) {
  59. ct := newConnTracker(10, time.Microsecond)
  60. for i := 0; i < 10; i++ {
  61. ip := randLocalIPv4()
  62. require.NoError(t, ct.AddConn(ip))
  63. time.Sleep(2 * time.Microsecond)
  64. require.NoError(t, ct.AddConn(ip))
  65. }
  66. require.Equal(t, 10, ct.Len())
  67. })
  68. }