From 2d51d31b8a6759cb6d83af6967d4fdb4f1b29b3b Mon Sep 17 00:00:00 2001 From: salvacybersec Date: Mon, 6 Apr 2026 17:28:05 +0300 Subject: [PATCH] test(17-01): add unit tests for Bot creation and auth filtering - TestNew_EmptyToken: verify empty token returns error from telego - TestIsAllowed_EmptyList: verify open access when no restrictions set - TestIsAllowed_RestrictedList: verify allowlist filtering - TestCheckRateLimit: verify cooldown enforcement and per-user isolation --- pkg/bot/bot_test.go | 56 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 pkg/bot/bot_test.go diff --git a/pkg/bot/bot_test.go b/pkg/bot/bot_test.go new file mode 100644 index 0000000..5195f01 --- /dev/null +++ b/pkg/bot/bot_test.go @@ -0,0 +1,56 @@ +package bot + +import ( + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNew_EmptyToken(t *testing.T) { + _, err := New(Config{Token: ""}) + require.Error(t, err, "New with empty token should return an error") +} + +func TestIsAllowed_EmptyList(t *testing.T) { + b := &Bot{ + cfg: Config{AllowedChats: nil}, + } + assert.True(t, b.isAllowed(12345), "empty AllowedChats should allow any chat ID") + assert.True(t, b.isAllowed(0), "empty AllowedChats should allow zero chat ID") + assert.True(t, b.isAllowed(-999), "empty AllowedChats should allow negative chat ID") +} + +func TestIsAllowed_RestrictedList(t *testing.T) { + b := &Bot{ + cfg: Config{AllowedChats: []int64{100, 200}}, + } + assert.True(t, b.isAllowed(100), "chat 100 should be allowed") + assert.True(t, b.isAllowed(200), "chat 200 should be allowed") + assert.False(t, b.isAllowed(999), "chat 999 should not be allowed") + assert.False(t, b.isAllowed(0), "chat 0 should not be allowed") +} + +func TestCheckRateLimit(t *testing.T) { + b := &Bot{ + rateLimits: make(map[int64]time.Time), + } + + cooldown := 60 * time.Second + + // First call should be allowed. + assert.True(t, b.checkRateLimit(1, cooldown), "first call should pass rate limit") + + // Immediate second call should be blocked. + assert.False(t, b.checkRateLimit(1, cooldown), "immediate second call should be rate limited") + + // Different user should not be affected. + assert.True(t, b.checkRateLimit(2, cooldown), "different user should pass rate limit") + + // After cooldown expires, the same user should be allowed again. + b.rateMu.Lock() + b.rateLimits[1] = time.Now().Add(-61 * time.Second) + b.rateMu.Unlock() + assert.True(t, b.checkRateLimit(1, cooldown), "should pass after cooldown expires") +}