Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

throttler_test.go 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright (c) 2018 Shivaram Lingamneni
  2. // released under the MIT license
  3. package connection_limits
  4. import (
  5. "net"
  6. "reflect"
  7. "testing"
  8. "time"
  9. )
  10. func assertEqual(supplied, expected interface{}, t *testing.T) {
  11. if !reflect.DeepEqual(supplied, expected) {
  12. t.Errorf("expected %v but got %v", expected, supplied)
  13. }
  14. }
  15. func TestGenericThrottle(t *testing.T) {
  16. minute, _ := time.ParseDuration("1m")
  17. second, _ := time.ParseDuration("1s")
  18. zero, _ := time.ParseDuration("0s")
  19. throttler := GenericThrottle{
  20. Duration: minute,
  21. Limit: 2,
  22. }
  23. now := time.Now()
  24. throttled, remaining := throttler.touch(now)
  25. assertEqual(throttled, false, t)
  26. assertEqual(remaining, zero, t)
  27. now = now.Add(second)
  28. throttled, remaining = throttler.touch(now)
  29. assertEqual(throttled, false, t)
  30. assertEqual(remaining, zero, t)
  31. now = now.Add(second)
  32. throttled, remaining = throttler.touch(now)
  33. assertEqual(throttled, true, t)
  34. assertEqual(remaining, 58*second, t)
  35. now = now.Add(minute)
  36. throttled, remaining = throttler.touch(now)
  37. assertEqual(throttled, false, t)
  38. assertEqual(remaining, zero, t)
  39. }
  40. func TestGenericThrottleDisabled(t *testing.T) {
  41. minute, _ := time.ParseDuration("1m")
  42. throttler := GenericThrottle{
  43. Duration: minute,
  44. Limit: 0,
  45. }
  46. for i := 0; i < 1024; i += 1 {
  47. throttled, _ := throttler.Touch()
  48. if throttled {
  49. t.Error("disabled throttler should not throttle")
  50. }
  51. }
  52. }
  53. func TestConnectionThrottle(t *testing.T) {
  54. minute, _ := time.ParseDuration("1m")
  55. maxConnections := 3
  56. config := ThrottlerConfig{
  57. Enabled: true,
  58. CidrLenIPv4: 32,
  59. CidrLenIPv6: 64,
  60. ConnectionsPerCidr: maxConnections,
  61. Duration: minute,
  62. }
  63. throttler := NewThrottler()
  64. throttler.ApplyConfig(config)
  65. addr := net.ParseIP("8.8.8.8")
  66. for i := 0; i < maxConnections; i += 1 {
  67. err := throttler.AddClient(addr)
  68. assertEqual(err, nil, t)
  69. }
  70. err := throttler.AddClient(addr)
  71. assertEqual(err, errTooManyClients, t)
  72. }