bucket_manager_test.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package golimiter
  2. import (
  3. "testing"
  4. "time"
  5. )
  6. func TestTokenBucketManager(t *testing.T) {
  7. tbManager := NewTokenBucketManager()
  8. tb, err := tbManager.CreateTokenBucket("127.0.0.1", 10, 5, time.Second)
  9. if err != nil {
  10. t.Fatalf("Failed to create token bucket: %v", err)
  11. }
  12. foundBucket := tbManager.GetTokenBucket("127.0.0.1")
  13. if foundBucket != tb {
  14. t.Error("Retrieved token bucket does not match created bucket")
  15. }
  16. nonExistentBucket := tbManager.GetTokenBucket("192.168.1.1")
  17. if nonExistentBucket != nil {
  18. t.Error("Expected nil for non-existent token bucket")
  19. }
  20. }
  21. func TestTokenBucketCleanup(t *testing.T) {
  22. tbManager := NewTokenBucketManager()
  23. tbManager.CreateTokenBucket("127.0.0.1", 10, 5, 2*time.Second)
  24. time.Sleep(3 * time.Second)
  25. go tbManager.StartCleanupTask(time.Second)
  26. // Wait for cleanup to run
  27. time.Sleep(2 * time.Second)
  28. tb := tbManager.GetTokenBucket("127.0.0.1")
  29. if tb != nil {
  30. t.Error("Expired token bucket was not cleaned up")
  31. }
  32. }