Skip to content

Commit

Permalink
test(comms): Update handler tests with improved mocking and safer tes…
Browse files Browse the repository at this point in the history
…t values

- Update mock values in test configurations
- Improve mocking patterns in handler tests
- Use consistent mocking approach across platform handlers
- Fix Field usage in MockConfig

Co-Authored-By: [email protected] <[email protected]>
  • Loading branch information
devin-ai-integration[bot] and marklysze committed Jan 29, 2025
1 parent 7a1cb91 commit 6c1acb6
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 46 deletions.
4 changes: 2 additions & 2 deletions test/agentchat/contrib/test_comms_platform_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ def __init__(self, name: str, **kwargs):
"config_list": [{"model": "gpt-4", "api_key": "fake-key"}]
}
class MockConfig(BaseCommsPlatformConfig):
timeout_minutes: int = Field(default=1, gt=0)
max_reply_messages: int = Field(default=1, gt=0)
timeout_minutes: int = 1
max_reply_messages: int = 1

def validate_config(self) -> bool:
return True
Expand Down
24 changes: 12 additions & 12 deletions test/agentchat/contrib/test_slack_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import threading
from typing import Dict, List, Optional, Union, Tuple

from autogen.agentchat.contrib.comms.slack_agent import SlackHandler
from autogen.agentchat.contrib.comms.slack_agent import SlackHandler, SlackConfig
from autogen.agentchat.contrib.comms.platform_errors import (
PlatformAuthenticationError,
PlatformConnectionError,
Expand All @@ -15,20 +15,20 @@

@pytest.fixture
def slack_handler():
handler = SlackHandler(bot_token="xoxb-fake", channel_id="ABC123", signing_secret="secret")
handler._client = MagicMock()
handler._client.chat_postMessage = AsyncMock()
handler._loop = asyncio.new_event_loop()
handler._thread = threading.current_thread()
handler._message_replies = {}
handler.silent = False
return handler
config = SlackConfig(bot_token="mock_test_token", channel_id="mock_channel", signing_secret="mock_secret")
handler = SlackHandler(config=config)
with patch.object(handler, '_slack_client', new=MagicMock()) as mock_client:
mock_client.chat_postMessage = AsyncMock()
with patch.object(handler, '_ready', new=asyncio.Event()) as ready_event:
ready_event.set()
return handler

@pytest.mark.asyncio
async def test_slack_handler_start(slack_handler):
slack_handler._client.auth_test = AsyncMock(return_value={"ok": True})
assert await slack_handler.start() is True
slack_handler._client.auth_test.assert_called_once()
with patch.object(slack_handler, '_client') as mock_client:
mock_client.auth_test = AsyncMock(return_value={"ok": True})
assert await slack_handler.start() is True
mock_client.auth_test.assert_called_once()

@pytest.mark.asyncio
async def test_slack_handler_start_auth_error(slack_handler):
Expand Down
69 changes: 37 additions & 32 deletions test/agentchat/contrib/test_telegram_handler.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import pytest
from unittest.mock import MagicMock, AsyncMock
from unittest.mock import MagicMock, AsyncMock, patch
import telegram
import asyncio
import threading
from typing import Dict, List, Optional, Union, Tuple

from autogen.agentchat.contrib.comms.telegram_agent import TelegramHandler
from autogen.agentchat.contrib.comms.telegram_agent import TelegramHandler, TelegramConfig
from autogen.agentchat.contrib.comms.platform_errors import (
PlatformAuthenticationError,
PlatformConnectionError,
Expand All @@ -15,32 +15,34 @@

@pytest.fixture
def telegram_handler():
handler = TelegramHandler(bot_token="123456:ABC-DEF", destination_id="@testchannel")
handler._bot = MagicMock()
handler._bot.send_message = AsyncMock()
handler._loop = asyncio.new_event_loop()
handler._thread = threading.current_thread()
handler._message_replies = {}
handler.silent = False
return handler
config = TelegramConfig(bot_token="mock_test_token", destination_id="mock_channel")
handler = TelegramHandler(config=config)
with patch.object(handler, '_telegram_client', new=MagicMock()) as mock_client:
mock_client.send_message = AsyncMock()
with patch.object(handler, '_ready', new=asyncio.Event()) as ready_event:
ready_event.set()
return handler

@pytest.mark.asyncio
async def test_telegram_handler_start(telegram_handler):
telegram_handler._bot.get_me = AsyncMock(return_value=True)
assert await telegram_handler.start() is True
telegram_handler._bot.get_me.assert_called_once()
with patch.object(telegram_handler, '_bot') as mock_bot:
mock_bot.get_me = AsyncMock(return_value=True)
assert await telegram_handler.start() is True
mock_bot.get_me.assert_called_once()

@pytest.mark.asyncio
async def test_telegram_handler_start_auth_error(telegram_handler):
telegram_handler._bot.get_me = AsyncMock(side_effect=telegram.error.InvalidToken())
with pytest.raises(PlatformAuthenticationError):
await telegram_handler.start()
with patch.object(telegram_handler, '_bot') as mock_bot:
mock_bot.get_me = AsyncMock(side_effect=telegram.error.InvalidToken())
with pytest.raises(PlatformAuthenticationError):
await telegram_handler.start()

@pytest.mark.asyncio
async def test_telegram_handler_send_message(telegram_handler):
telegram_handler._bot.send_message = AsyncMock(
return_value=MagicMock(message_id=123)
)
with patch.object(telegram_handler, '_bot') as mock_bot:
mock_bot.send_message = AsyncMock(
return_value=MagicMock(message_id=123)
)
result = await telegram_handler.send_message("Test message")
assert result == ("Message sent successfully", "123")
telegram_handler._bot.send_message.assert_called_once_with(
Expand All @@ -52,30 +54,33 @@ async def test_telegram_handler_send_message(telegram_handler):
@pytest.mark.asyncio
async def test_telegram_handler_send_long_message(telegram_handler):
long_message = "x" * 4097 # Telegram's limit is 4096
telegram_handler._bot.send_message = AsyncMock(
side_effect=[
MagicMock(message_id=123),
MagicMock(message_id=124)
]
)
with patch.object(telegram_handler, '_bot') as mock_bot:
mock_bot.send_message = AsyncMock(
side_effect=[
MagicMock(message_id=123),
MagicMock(message_id=124)
]
)
result = await telegram_handler.send_message(long_message)
assert result[0] == "Message sent successfully"
assert telegram_handler._bot.send_message.call_count == 2
assert mock_bot.send_message.call_count == 2

@pytest.mark.asyncio
async def test_telegram_handler_send_message_rate_limit(telegram_handler):
telegram_handler._bot.send_message = AsyncMock(
side_effect=telegram.error.RetryAfter(5)
)
with patch.object(telegram_handler, '_bot') as mock_bot:
mock_bot.send_message = AsyncMock(
side_effect=telegram.error.RetryAfter(5)
)
with pytest.raises(PlatformRateLimitError) as exc_info:
await telegram_handler.send_message("Test message")
assert exc_info.value.retry_after == 5

@pytest.mark.asyncio
async def test_telegram_handler_send_message_network_error(telegram_handler):
telegram_handler._bot.send_message = AsyncMock(
side_effect=telegram.error.NetworkError()
)
with patch.object(telegram_handler, '_bot') as mock_bot:
mock_bot.send_message = AsyncMock(
side_effect=telegram.error.NetworkError()
)
with pytest.raises(PlatformConnectionError):
await telegram_handler.send_message("Test message")

Expand Down

0 comments on commit 6c1acb6

Please sign in to comment.