Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

Fix : Restore Async Usage in Outlook Mail Toolkit (#3623)

Tanuj Taneja0c7b9355f790
diff --git a/camel/toolkits/function_tool.py b/camel/toolkits/function_tool.py
index ccdeba279..50313003d 100644
--- a/camel/toolkits/function_tool.py
+++ b/camel/toolkits/function_tool.py
@@ -17,6 +17,7 @@ import functools
import inspect
import logging
import textwrap
+import threading
import warnings
from concurrent.futures import ThreadPoolExecutor
from inspect import Parameter, getsource, signature
@@ -37,6 +38,10 @@ logger = logging.getLogger(__name__)
# Shared thread pool for running sync tools without blocking the event loop
_SYNC_TOOL_EXECUTOR = ThreadPoolExecutor(max_workers=64)
+# Persistent event loop to avoid httpx connection pool issues
+_PERSISTENT_LOOP: Optional[asyncio.AbstractEventLoop] = None
+_PERSISTENT_LOOP_LOCK = threading.Lock()
+
def _remove_a_key(d: Dict, remove_key: Any) -> None:
r"""Remove a key from a dictionary recursively."""
@@ -482,37 +487,102 @@ class FunctionTool:
if self.synthesize_output:
result = self.synthesize_execution_output(args, kwargs)
return result
- else:
- # Pass the extracted arguments to the indicated function
+
+ # Call the function first
+ try:
+ result = self.func(*args, **kwargs)
+ except Exception as e:
+ parts = []
+ if args:
+ parts.append(f"args={args}")
+ if kwargs:
+ parts.append(f"kwargs={kwargs}")
+ args_str = ", ".join(parts) if parts else "no arguments"
+ raise ValueError(
+ f"Execution of function {self.func.__name__} failed with "
+ f"{args_str}. Error: {e}"
+ )
+
+ # Handle coroutine result (from async function or sync wrapper
+ # returning coroutine)
+ if inspect.iscoroutine(result):
+ # Check if there's already a running event loop
try:
- result = self.func(*args, **kwargs)
- return result
- except Exception as e:
- parts = []
- if args:
- parts.append(f"args={args}")
- if kwargs:
- parts.append(f"kwargs={kwargs}")
- args_str = ", ".join(parts) if parts else "no arguments"
- raise ValueError(
- f"Execution of function {self.func.__name__} failed with "
- f"{args_str}. Error: {e}"
+ asyncio.get_running_loop()
+ has_running_loop = True
+ except RuntimeError:
+ has_running_loop = False
+
+ if has_running_loop:
+ # Already in an async context
+ warnings.warn(
+ f"Async tool '{self.func.__name__}' is being called "
+ f"synchronously within an async context. Consider using "
+ f"'await tool.async_call()' or 'await agent.astep()' for "
+ f"better performance.",
+ RuntimeWarning,
+ stacklevel=2,
+ )
+ # Must run in separate thread to avoid blocking current loop
+ future = _SYNC_TOOL_EXECUTOR.submit(
+ self._run_async_in_persistent_loop, result
+ )
+ return future.result()
+ else:
+ warnings.warn(
+ f"Async tool '{self.func.__name__}' is being called "
+ f"synchronously. Consider using 'await tool.async_call()' "
+ f"or 'await agent.astep()' for better performance.",
+ RuntimeWarning,
+ stacklevel=2,
)
+ return self._run_async_in_persistent_loop(result)
+
+ return result
+
+ @staticmethod
+ def _run_async_in_persistent_loop(coro):
+ r"""Run coroutine in persistent loop to preserve httpx connections."""
+ global _PERSISTENT_LOOP
+ with _PERSISTENT_LOOP_LOCK:
+ need_new_loop = (
+ _PERSISTENT_LOOP is None
+ or _PERSISTENT_LOOP.is_closed()
+ or not _PERSISTENT_LOOP.is_running()
+ )
+ if need_new_loop:
+ _PERSISTENT_LOOP = asyncio.new_event_loop()
+ t = threading.Thread(
+ target=_PERSISTENT_LOOP.run_forever, daemon=True
+ )
+ t.start()
+ while not _PERSISTENT_LOOP.is_running():
+ pass # Wait for loop to start
+ future = asyncio.run_coroutine_threadsafe(coro, _PERSISTENT_LOOP)
+ return future.result()
async def async_call(self, *args: Any, **kwargs: Any) -> Any:
if self.synthesize_output:
result = self.synthesize_execution_output(args, kwargs)
return result
- if self.is_async:
+
+ # Check if the function itself (not unwrapped) is a coroutine function
+ if inspect.iscoroutinefunction(self.func):
return await self.func(*args, **kwargs)
- else:
- # Run sync function in executor to avoid blocking event loop
- # Use functools.partial to properly capture args/kwargs
- loop = asyncio.get_running_loop()
- return await loop.run_in_executor(
- _SYNC_TOOL_EXECUTOR,
- functools.partial(self.func, *args, **kwargs),
- )
+
+ # For sync functions (including sync wrappers around async functions),
+ # run in executor to avoid blocking
+ loop = asyncio.get_running_loop()
+ result = await loop.run_in_executor(
+ _SYNC_TOOL_EXECUTOR,
+ functools.partial(self.func, *args, **kwargs),
+ )
+
+ # If the sync wrapper returned a coroutine, await it
+ if inspect.iscoroutine(result):
+ return await result
+
+ return result
@property
def is_async(self) -> bool:
diff --git a/camel/toolkits/microsoft_outlook_mail_toolkit.py b/camel/toolkits/microsoft_outlook_mail_toolkit.py
index 7545e578c..ae8584f24 100644
--- a/camel/toolkits/microsoft_outlook_mail_toolkit.py
+++ b/camel/toolkits/microsoft_outlook_mail_toolkit.py
@@ -826,7 +826,7 @@ class OutlookMailToolkit(BaseToolkit):
return mail_message
- def outlook_send_email(
+ async def outlook_send_email(
self,
to_email: List[str],
subject: str,
@@ -896,7 +896,7 @@ class OutlookMailToolkit(BaseToolkit):
save_to_sent_items=save_to_sent_items,
)
- self.client.me.send_mail.post(request)
+ await self.client.me.send_mail.post(request)
logger.info("Email sent successfully.")
return {
@@ -909,7 +909,7 @@ class OutlookMailToolkit(BaseToolkit):
logger.exception("Failed to send email")
return {"error": f"Failed to send email: {e!s}"}
- def outlook_create_draft_email(
+ async def outlook_create_draft_email(
self,
to_email: List[str],
subject: str,
@@ -968,7 +968,7 @@ class OutlookMailToolkit(BaseToolkit):
reply_to=reply_to,
)
- result = self.client.me.messages.post(request_body)
+ result = await self.client.me.messages.post(request_body)
logger.info("Draft email created successfully.")
return {
@@ -983,7 +983,7 @@ class OutlookMailToolkit(BaseToolkit):
logger.error(error_msg)
return {"error": error_msg}
- def outlook_send_draft_email(self, draft_id: str) -> Dict[str, Any]:
+ async def outlook_send_draft_email(self, draft_id: str) -> Dict[str, Any]:
"""Sends a draft email via Microsoft Outlook.
Args:
@@ -997,7 +997,7 @@ class OutlookMailToolkit(BaseToolkit):
email sending operation.
"""
try:
- self.client.me.messages.by_message_id(draft_id).send.post()
+ await self.client.me.messages.by_message_id(draft_id).send.post()
logger.info(f"Draft email with ID {draft_id} sent successfully.")
return {
@@ -1010,7 +1010,7 @@ class OutlookMailToolkit(BaseToolkit):
logger.error(error_msg)
return {"error": error_msg}
- def outlook_delete_email(self, message_id: str) -> Dict[str, Any]:
+ async def outlook_delete_email(self, message_id: str) -> Dict[str, Any]:
"""Deletes an email from Microsoft Outlook.
Args:
@@ -1023,7 +1023,7 @@ class OutlookMailToolkit(BaseToolkit):
deletion operation.
"""
try:
- self.client.me.messages.by_message_id(message_id).delete()
+ await self.client.me.messages.by_message_id(message_id).delete()
logger.info(f"Email with ID {message_id} deleted successfully.")
return {
'status': 'success',
@@ -1035,7 +1035,7 @@ class OutlookMailToolkit(BaseToolkit):
logger.error(error_msg)
return {"error": error_msg}
- def outlook_move_message_to_folder(
+ async def outlook_move_message_to_folder(
self, message_id: str, destination_folder_id: str
) -> Dict[str, Any]:
"""Moves an email to a specified folder in Microsoft Outlook.
@@ -1062,7 +1062,7 @@ class OutlookMailToolkit(BaseToolkit):
destination_id=destination_folder_id,
)
message = self.client.me.messages.by_message_id(message_id)
- message.move.post(request_body)
+ await message.move.post(request_body)
logger.info(
f"Email with ID {message_id} moved to folder "
@@ -1079,7 +1079,7 @@ class OutlookMailToolkit(BaseToolkit):
logger.error(error_msg)
return {"error": error_msg}
- def outlook_get_attachments(
+ async def outlook_get_attachments(
self,
message_id: str,
metadata_only: bool = True,
@@ -1120,7 +1120,7 @@ class OutlookMailToolkit(BaseToolkit):
if metadata_only:
request_config = self._build_attachment_query()
- attachments_response = self._fetch_attachments(
+ attachments_response = await self._fetch_attachments(
message_id, request_config
)
if not attachments_response:
@@ -1180,7 +1180,7 @@ class OutlookMailToolkit(BaseToolkit):
query_parameters=query_params
)
- def _fetch_attachments(
+ async def _fetch_attachments(
self, message_id: str, request_config: Optional[Any] = None
):
"""Fetches attachments from the Microsoft Graph API.
@@ -1195,10 +1195,10 @@ class OutlookMailToolkit(BaseToolkit):
Attachments response from the Graph API.
"""
if not request_config:
- return self.client.me.messages.by_message_id(
+ return await self.client.me.messages.by_message_id(
message_id
).attachments.get()
- return self.client.me.messages.by_message_id(
+ return await self.client.me.messages.by_message_id(
message_id
).attachments.get(request_configuration=request_config)
@@ -1334,7 +1334,7 @@ class OutlookMailToolkit(BaseToolkit):
recipients.append({'address': email, 'name': name})
return recipients
- def _extract_message_details(
+ async def _extract_message_details(
self,
message: Any,
return_html_content: bool = False,
@@ -1432,7 +1432,7 @@ class OutlookMailToolkit(BaseToolkit):
if not include_attachments:
return details
- attachments_info = self.outlook_get_attachments(
+ attachments_info = await self.outlook_get_attachments(
message_id=details['message_id'],
metadata_only=attachment_metadata_only,
include_inline_attachments=include_inline_attachments,
@@ -1446,7 +1446,7 @@ class OutlookMailToolkit(BaseToolkit):
logger.error(error_msg)
raise ValueError(error_msg)
- def outlook_get_message(
+ async def outlook_get_message(
self,
message_id: str,
return_html_content: bool = False,
@@ -1491,14 +1491,16 @@ class OutlookMailToolkit(BaseToolkit):
is_read, is_draft, body_preview, and optionally attachments.
"""
try:
- message = self.client.me.messages.by_message_id(message_id).get()
+ message = await self.client.me.messages.by_message_id(
+ message_id
+ ).get()
if not message:
error_msg = f"Message with ID {message_id} not found"
logger.error(error_msg)
return {"error": error_msg}
- details = self._extract_message_details(
+ details = await self._extract_message_details(
message=message,
return_html_content=return_html_content,
include_attachments=include_attachments,
@@ -1518,7 +1520,7 @@ class OutlookMailToolkit(BaseToolkit):
logger.error(error_msg)
return {"error": error_msg}
- def _get_messages_from_folder(
+ async def _get_messages_from_folder(
self,
folder_id: str,
request_config,
@@ -1533,7 +1535,7 @@ class OutlookMailToolkit(BaseToolkit):
Messages response from the Graph API, or None if folder not found.
"""
try:
- messages = self.client.me.mail_folders.by_mail_folder_id(
+ messages = await self.client.me.mail_folders.by_mail_folder_id(
folder_id
).messages.get(request_configuration=request_config)
return messages
@@ -1543,7 +1545,7 @@ class OutlookMailToolkit(BaseToolkit):
)
return None
- def outlook_list_messages(
+ async def outlook_list_messages(
self,
folder_ids: Optional[List[str]] = None,
filter_query: Optional[str] = None,
@@ -1625,13 +1627,13 @@ class OutlookMailToolkit(BaseToolkit):
)
if not folder_ids:
# Search entire mailbox in a single API call
- messages_response = self.client.me.messages.get(
+ messages_response = await self.client.me.messages.get(
request_configuration=request_config
)
all_messages = []
if messages_response and messages_response.value:
for message in messages_response.value:
- details = self._extract_message_details(
+ details = await self._extract_message_details(
message=message,
return_html_content=return_html_content,
include_attachments=include_attachment_metadata,
@@ -1656,7 +1658,7 @@ class OutlookMailToolkit(BaseToolkit):
# Search specific folders (requires multiple API calls)
all_messages = []
for folder_id in folder_ids:
- messages_response = self._get_messages_from_folder(
+ messages_response = await self._get_messages_from_folder(
folder_id=folder_id,
request_config=request_config,
)
@@ -1666,7 +1668,7 @@ class OutlookMailToolkit(BaseToolkit):
# Extract details from each message
for message in messages_response.value:
- details = self._extract_message_details(
+ details = await self._extract_message_details(
message=message,
return_html_content=return_html_content,
include_attachments=include_attachment_metadata,
@@ -1695,7 +1697,7 @@ class OutlookMailToolkit(BaseToolkit):
logger.error(error_msg)
return {"error": error_msg}
- def outlook_reply_to_email(
+ async def outlook_reply_to_email(
self,
message_id: str,
content: str,
@@ -1730,10 +1732,10 @@ class OutlookMailToolkit(BaseToolkit):
request_body_reply_all = ReplyAllPostRequestBody(
comment=content
)
- message_request.reply_all.post(request_body_reply_all)
+ await message_request.reply_all.post(request_body_reply_all)
else:
request_body = ReplyPostRequestBody(comment=content)
- message_request.reply.post(request_body)
+ await message_request.reply.post(request_body)
reply_type = "Reply All" if reply_all else "Reply"
logger.info(
@@ -1753,7 +1755,7 @@ class OutlookMailToolkit(BaseToolkit):
logger.error(error_msg)
return {"error": error_msg}
- def outlook_update_draft_message(
+ async def outlook_update_draft_message(
self,
message_id: str,
subject: Optional[str] = None,
@@ -1827,7 +1829,7 @@ class OutlookMailToolkit(BaseToolkit):
)
# Update the message using PATCH
- self.client.me.messages.by_message_id(message_id).patch(
+ await self.client.me.messages.by_message_id(message_id).patch(
mail_message
)
diff --git a/test/toolkits/test_microsoft_outlook_mail_toolkit.py b/test/toolkits/test_microsoft_outlook_mail_toolkit.py
index 02a6dcc62..be3cb5e98 100644
--- a/test/toolkits/test_microsoft_outlook_mail_toolkit.py
+++ b/test/toolkits/test_microsoft_outlook_mail_toolkit.py
@@ -14,7 +14,7 @@
import json
import os
-from unittest.mock import MagicMock, mock_open, patch
+from unittest.mock import AsyncMock, MagicMock, mock_open, patch
import pytest
@@ -26,7 +26,7 @@ from camel.toolkits.microsoft_outlook_mail_toolkit import (
@pytest.fixture
def mock_graph_service():
- """Mock Microsoft Graph API service."""
+ """Mock Microsoft Graph API service with async methods."""
with patch("msgraph.GraphServiceClient") as mock_service_client:
mock_client = MagicMock()
mock_service_client.return_value = mock_client
@@ -39,16 +39,16 @@ def mock_graph_service():
mock_messages = MagicMock()
mock_me.messages = mock_messages
- # Mock send_mail endpoint
+ # Mock send_mail endpoint (async)
mock_send_mail = MagicMock()
mock_me.send_mail = mock_send_mail
- mock_send_mail.post = MagicMock()
+ mock_send_mail.post = AsyncMock()
- # Mock messages.get for listing messages
- mock_messages.get = MagicMock()
+ # Mock messages.get for listing messages (async)
+ mock_messages.get = AsyncMock()
- # Mock messages.post for creating drafts
- mock_messages.post = MagicMock()
+ # Mock messages.post for creating drafts (async)
+ mock_messages.post = AsyncMock()
# Mock messages.by_message_id for specific message operations
mock_by_message_id = MagicMock()
@@ -56,39 +56,39 @@ def mock_graph_service():
return_value=mock_by_message_id
)
- # Mock get message by ID
- mock_by_message_id.get = MagicMock()
+ # Mock get message by ID (async)
+ mock_by_message_id.get = AsyncMock()
- # Mock send draft
+ # Mock send draft (async)
mock_send = MagicMock()
mock_by_message_id.send = mock_send
- mock_send.post = MagicMock()
+ mock_send.post = AsyncMock()
- # Mock delete message
- mock_by_message_id.delete = MagicMock()
+ # Mock delete message (async)
+ mock_by_message_id.delete = AsyncMock()
- # Mock move message
+ # Mock move message (async)
mock_move = MagicMock()
mock_by_message_id.move = mock_move
- mock_move.post = MagicMock()
+ mock_move.post = AsyncMock()
- # Mock attachments
+ # Mock attachments (async)
mock_attachments = MagicMock()
mock_by_message_id.attachments = mock_attachments
- mock_attachments.get = MagicMock()
+ mock_attachments.get = AsyncMock()
- # Mock reply endpoint
+ # Mock reply endpoint (async)
mock_reply = MagicMock()
mock_by_message_id.reply = mock_reply
- mock_reply.post = MagicMock()
+ mock_reply.post = AsyncMock()
- # Mock reply_all endpoint
+ # Mock reply_all endpoint (async)
mock_reply_all = MagicMock()
mock_by_message_id.reply_all = mock_reply_all
- mock_reply_all.post = MagicMock()
+ mock_reply_all.post = AsyncMock()
- # Mock patch endpoint for updating messages
- mock_by_message_id.patch = MagicMock()
+ # Mock patch endpoint for updating messages (async)
+ mock_by_message_id.patch = AsyncMock()
# Mock mail_folders for folder-specific operations
mock_mail_folders = MagicMock()
@@ -100,10 +100,10 @@ def mock_graph_service():
return_value=mock_by_folder_id
)
- # Mock folder messages
+ # Mock folder messages (async)
mock_folder_messages = MagicMock()
mock_by_folder_id.messages = mock_folder_messages
- mock_folder_messages.get = MagicMock()
+ mock_folder_messages.get = AsyncMock()
yield mock_client
@@ -145,11 +145,12 @@ def outlook_toolkit(mock_graph_service):
yield toolkit
-def test_send_email(outlook_toolkit, mock_graph_service):
+async def test_send_email(outlook_toolkit, mock_graph_service):
"""Test sending an email successfully."""
mock_graph_service.me.send_mail.post.return_value = None
- result = outlook_toolkit.outlook_send_email(
+ result = await outlook_toolkit.outlook_send_email(
to_email=['[email protected]'],
subject='Test Subject',
content='Test Body',
@@ -163,7 +164,10 @@ def test_send_email(outlook_toolkit, mock_graph_service):
mock_graph_service.me.send_mail.post.assert_called_once()
-def test_send_email_with_attachments(outlook_toolkit, mock_graph_service):
+async def test_send_email_with_attachments(
+ outlook_toolkit, mock_graph_service
+):
"""Test sending an email with attachments."""
mock_graph_service.me.send_mail.post.return_value = None
@@ -174,7 +178,7 @@ def test_send_email_with_attachments(outlook_toolkit, mock_graph_service):
mock_file = mock_file_open.return_value.__enter__.return_value
mock_file.read.return_value = b'test content'
- result = outlook_toolkit.outlook_send_email(
+ result = await outlook_toolkit.outlook_send_email(
to_email=['[email protected]'],
subject='Test Subject',
content='Test Body',
@@ -185,9 +189,10 @@ def test_send_email_with_attachments(outlook_toolkit, mock_graph_service):
mock_graph_service.me.send_mail.post.assert_called_once()
-def test_send_email_invalid_email(outlook_toolkit):
+async def test_send_email_invalid_email(outlook_toolkit):
"""Test sending email with invalid email address."""
- result = outlook_toolkit.outlook_send_email(
+ result = await outlook_toolkit.outlook_send_email(
to_email=['invalid-email'],
subject='Test Subject',
content='Test Body',
@@ -197,11 +202,12 @@ def test_send_email_invalid_email(outlook_toolkit):
assert 'Invalid email address' in result['error']
-def test_send_email_failure(outlook_toolkit, mock_graph_service):
+async def test_send_email_failure(outlook_toolkit, mock_graph_service):
"""Test sending email failure."""
mock_graph_service.me.send_mail.post.side_effect = Exception("API Error")
- result = outlook_toolkit.outlook_send_email(
+ result = await outlook_toolkit.outlook_send_email(
to_email=['[email protected]'],
subject='Test Subject',
content='Test Body',
@@ -211,13 +217,14 @@ def test_send_email_failure(outlook_toolkit, mock_graph_service):
assert 'Failed to send email' in result['error']
-def test_create_email_draft(outlook_toolkit, mock_graph_service):
+async def test_create_email_draft(outlook_toolkit, mock_graph_service):
"""Test creating an email draft."""
mock_draft_result = MagicMock()
mock_draft_result.id = 'draft123'
mock_graph_service.me.messages.post.return_value = mock_draft_result
- result = outlook_toolkit.outlook_create_draft_email(
+ result = await outlook_toolkit.outlook_create_draft_email(
to_email=['[email protected]'],
subject='Test Subject',
content='Test Body',
@@ -269,7 +276,8 @@ def test_browser_auth_persists_refresh_token(tmp_path):
assert token_data["refresh_token"] == "mock_refresh_token"
-def test_create_email_draft_with_attachments(
+async def test_create_email_draft_with_attachments(
outlook_toolkit, mock_graph_service
):
"""Test creating an email draft with attachments."""
@@ -284,7 +292,7 @@ def test_create_email_draft_with_attachments(
mock_file = mock_file_open.return_value.__enter__.return_value
mock_file.read.return_value = b'test content'
- result = outlook_toolkit.outlook_create_draft_email(
+ result = await outlook_toolkit.outlook_create_draft_email(
to_email=['[email protected]'],
subject='Test Subject',
content='Test Body',
@@ -296,9 +304,10 @@ def test_create_email_draft_with_attachments(
mock_graph_service.me.messages.post.assert_called_once()
-def test_create_email_draft_invalid_email(outlook_toolkit):
+async def test_create_email_draft_invalid_email(outlook_toolkit):
"""Test creating draft with invalid email address."""
- result = outlook_toolkit.outlook_create_draft_email(
+ result = await outlook_toolkit.outlook_create_draft_email(
to_email=['invalid-email'],
subject='Test Subject',
content='Test Body',
@@ -308,11 +317,12 @@ def test_create_email_draft_invalid_email(outlook_toolkit):
assert 'Invalid email address' in result['error']
-def test_create_email_draft_failure(outlook_toolkit, mock_graph_service):
+async def test_create_email_draft_failure(outlook_toolkit, mock_graph_service):
"""Test creating email draft failure."""
mock_graph_service.me.messages.post.side_effect = Exception("API Error")
- result = outlook_toolkit.outlook_create_draft_email(
+ result = await outlook_toolkit.outlook_create_draft_email(
to_email=['[email protected]'],
subject='Test Subject',
content='Test Body',
@@ -322,13 +332,16 @@ def test_create_email_draft_failure(outlook_toolkit, mock_graph_service):
assert 'Failed to create draft email' in result['error']
-def test_send_draft_email(outlook_toolkit, mock_graph_service):
+async def test_send_draft_email(outlook_toolkit, mock_graph_service):
"""Test sending a draft email."""
mock_graph_service.me.messages.by_message_id().send.post.return_value = (
None
)
- result = outlook_toolkit.outlook_send_draft_email(draft_id='draft123')
+ result = await outlook_toolkit.outlook_send_draft_email(
+ draft_id='draft123'
+ )
assert result['status'] == 'success'
assert result['message'] == 'Draft email sent successfully'
@@ -337,23 +350,27 @@ def test_send_draft_email(outlook_toolkit, mock_graph_service):
mock_graph_service.me.messages.by_message_id().send.post.assert_called_once()
-def test_send_draft_email_failure(outlook_toolkit, mock_graph_service):
+async def test_send_draft_email_failure(outlook_toolkit, mock_graph_service):
"""Test sending draft email failure."""
mock_graph_service.me.messages.by_message_id().send.post.side_effect = (
Exception("API Error")
)
- result = outlook_toolkit.outlook_send_draft_email(draft_id='draft123')
+ result = await outlook_toolkit.outlook_send_draft_email(
+ draft_id='draft123'
+ )
assert 'error' in result
assert 'Failed to send draft email' in result['error']
-def test_delete_email(outlook_toolkit, mock_graph_service):
+async def test_delete_email(outlook_toolkit, mock_graph_service):
"""Test deleting an email successfully."""
mock_graph_service.me.messages.by_message_id().delete.return_value = None
- result = outlook_toolkit.outlook_delete_email(message_id='msg123')
+ result = await outlook_toolkit.outlook_delete_email(message_id='msg123')
assert result['status'] == 'success'
assert result['message'] == 'Email deleted successfully'
@@ -362,25 +379,27 @@ def test_delete_email(outlook_toolkit, mock_graph_service):
mock_graph_service.me.messages.by_message_id().delete.assert_called_once()
-def test_delete_email_failure(outlook_toolkit, mock_graph_service):
+async def test_delete_email_failure(outlook_toolkit, mock_graph_service):
"""Test deleting email failure."""
mock_graph_service.me.messages.by_message_id().delete.side_effect = (
Exception("API Error")
)
- result = outlook_toolkit.outlook_delete_email(message_id='msg123')
+ result = await outlook_toolkit.outlook_delete_email(message_id='msg123')
assert 'error' in result
assert 'Failed to delete email' in result['error']
-def test_move_message_to_folder(outlook_toolkit, mock_graph_service):
+async def test_move_message_to_folder(outlook_toolkit, mock_graph_service):
"""Test moving an email to a folder successfully."""
mock_graph_service.me.messages.by_message_id().move.post.return_value = (
None
)
- result = outlook_toolkit.outlook_move_message_to_folder(
+ result = await outlook_toolkit.outlook_move_message_to_folder(
message_id='msg123', destination_folder_id='inbox'
)
@@ -392,13 +411,16 @@ def test_move_message_to_folder(outlook_toolkit, mock_graph_service):
mock_graph_service.me.messages.by_message_id().move.post.assert_called_once()
-def test_move_message_to_folder_failure(outlook_toolkit, mock_graph_service):
+async def test_move_message_to_folder_failure(
+ outlook_toolkit, mock_graph_service
+):
"""Test moving email failure."""
mock_graph_service.me.messages.by_message_id().move.post.side_effect = (
Exception("API Error")
)
- result = outlook_toolkit.outlook_move_message_to_folder(
+ result = await outlook_toolkit.outlook_move_message_to_folder(
message_id='msg123', destination_folder_id='inbox'
)
@@ -406,7 +428,8 @@ def test_move_message_to_folder_failure(outlook_toolkit, mock_graph_service):
assert 'Failed to move email' in result['error']
-def test_get_attachments(outlook_toolkit, mock_graph_service):
+async def test_get_attachments(outlook_toolkit, mock_graph_service):
"""Test getting attachments and saving to disk."""
import base64
@@ -425,7 +448,7 @@ def test_get_attachments(outlook_toolkit, mock_graph_service):
patch('os.path.exists', return_value=False),
patch('builtins.open', create=True),
):
- result = outlook_toolkit.outlook_get_attachments(
+ result = await outlook_toolkit.outlook_get_attachments(
message_id='msg123',
)
@@ -433,7 +456,10 @@ def test_get_attachments(outlook_toolkit, mock_graph_service):
assert result['total_count'] == 1
-def test_get_attachments_exclude_inline(outlook_toolkit, mock_graph_service):
+async def test_get_attachments_exclude_inline(
+ outlook_toolkit, mock_graph_service
+):
"""Test getting attachments excluding inline attachments (default)."""
mock_attachment1 = MagicMock()
mock_attachment1.name = 'image.png'
@@ -444,7 +470,7 @@ def test_get_attachments_exclude_inline(outlook_toolkit, mock_graph_service):
mock_attachments = mock_graph_service.me.messages.by_message_id()
mock_attachments.attachments.get.return_value = mock_response
- result = outlook_toolkit.outlook_get_attachments(
+ result = await outlook_toolkit.outlook_get_attachments(
message_id='msg123',
include_inline_attachments=False,
)
@@ -454,7 +480,10 @@ def test_get_attachments_exclude_inline(outlook_toolkit, mock_graph_service):
assert not result['attachments']
-def test_get_attachments_include_inline(outlook_toolkit, mock_graph_service):
+async def test_get_attachments_include_inline(
+ outlook_toolkit, mock_graph_service
+):
"""Test getting attachments including inline attachments."""
mock_attachment1 = MagicMock()
mock_attachment1.name = 'document.pdf'
@@ -469,7 +498,7 @@ def test_get_attachments_include_inline(outlook_toolkit, mock_graph_service):
mock_attachments = mock_graph_service.me.messages.by_message_id()
mock_attachments.attachments.get.return_value = mock_response
- result = outlook_toolkit.outlook_get_attachments(
+ result = await outlook_toolkit.outlook_get_attachments(
message_id='msg123',
metadata_only=True,
include_inline_attachments=True,
@@ -481,18 +510,20 @@ def test_get_attachments_include_inline(outlook_toolkit, mock_graph_service):
assert result['attachments'][1]['name'] == 'image.png'
-def test_get_attachments_failure(outlook_toolkit, mock_graph_service):
+async def test_get_attachments_failure(outlook_toolkit, mock_graph_service):
"""Test getting attachments failure."""
mock_attachments = mock_graph_service.me.messages.by_message_id()
mock_attachments.attachments.get.side_effect = Exception("API Error")
- result = outlook_toolkit.outlook_get_attachments(message_id='msg123')
+ result = await outlook_toolkit.outlook_get_attachments(message_id='msg123')
assert 'error' in result
assert 'Failed to get attachments' in result['error']
-def test_get_attachments_with_content_and_save_path(
+async def test_get_attachments_with_content_and_save_path(
outlook_toolkit, mock_graph_service
):
"""Test getting attachments with metadata_only=False and save_path."""
@@ -520,7 +551,7 @@ def test_get_attachments_with_content_and_save_path(
patch('os.path.exists', return_value=False),
patch('builtins.open', m_open),
):
- result = outlook_toolkit.outlook_get_attachments(
+ result = await outlook_toolkit.outlook_get_attachments(
message_id='msg456',
metadata_only=False,
save_path=temp_dir,
@@ -599,7 +630,10 @@ def create_mock_message(request):
return mock_msg
-def test_get_message(outlook_toolkit, mock_graph_service, create_mock_message):
+async def test_get_message(
+ outlook_toolkit, mock_graph_service, create_mock_message
+):
"""Test getting messages with different content types."""
with patch(
'camel.toolkits.microsoft_outlook_mail_toolkit.isinstance',
@@ -609,7 +643,7 @@ def test_get_message(outlook_toolkit, mock_graph_service, create_mock_message):
create_mock_message
)
- result = outlook_toolkit.outlook_get_message(message_id='msg123')
+ result = await outlook_toolkit.outlook_get_message(message_id='msg123')
assert result['status'] == 'success'
assert 'message' in result
@@ -625,19 +659,21 @@ def test_get_message(outlook_toolkit, mock_graph_service, create_mock_message):
mock_graph_service.me.messages.by_message_id().get.assert_called_once()
-def test_get_message_failure(outlook_toolkit, mock_graph_service):
+async def test_get_message_failure(outlook_toolkit, mock_graph_service):
"""Test get_message handles API errors correctly."""
mock_graph_service.me.messages.by_message_id().get.side_effect = Exception(
"API Error"
)
- result = outlook_toolkit.outlook_get_message(message_id='msg123')
+ result = await outlook_toolkit.outlook_get_message(message_id='msg123')
assert 'error' in result
assert 'Failed to get message' in result['error']
-def test_list_messages(
+async def test_list_messages(
outlook_toolkit, mock_graph_service, create_mock_message
):
"""Test listing messages with different content types."""
@@ -649,7 +685,7 @@ def test_list_messages(
mock_response.value = [create_mock_message]
mock_graph_service.me.messages.get.return_value = mock_response
- result = outlook_toolkit.outlook_list_messages()
+ result = await outlook_toolkit.outlook_list_messages()
assert result['status'] == 'success'
assert 'messages' in result
@@ -667,23 +703,25 @@ def test_list_messages(
mock_graph_service.me.messages.get.assert_called_once()
-def test_list_messages_failure(outlook_toolkit, mock_graph_service):
+async def test_list_messages_failure(outlook_toolkit, mock_graph_service):
"""Test list_messages handles API errors correctly."""
mock_graph_service.me.messages.get.side_effect = Exception("API Error")
- result = outlook_toolkit.outlook_list_messages()
+ result = await outlook_toolkit.outlook_list_messages()
assert 'error' in result
assert 'Failed to list messages' in result['error']
-def test_reply_to_email(outlook_toolkit, mock_graph_service):
+async def test_reply_to_email(outlook_toolkit, mock_graph_service):
"""Test replying to an email (reply to sender only)."""
mock_graph_service.me.messages.by_message_id().reply.post.return_value = (
None
)
- result = outlook_toolkit.outlook_reply_to_email(
+ result = await outlook_toolkit.outlook_reply_to_email(
message_id='msg123',
content='This is my reply',
reply_all=False,
@@ -698,12 +736,13 @@ def test_reply_to_email(outlook_toolkit, mock_graph_service):
mock_graph_service.me.messages.by_message_id().reply_all.post.assert_not_called()
-def test_reply_to_email_all(outlook_toolkit, mock_graph_service):
+async def test_reply_to_email_all(outlook_toolkit, mock_graph_service):
"""Test replying to all recipients of an email."""
mock_reply_all = mock_graph_service.me.messages.by_message_id().reply_all
mock_reply_all.post.return_value = None
- result = outlook_toolkit.outlook_reply_to_email(
+ result = await outlook_toolkit.outlook_reply_to_email(
message_id='msg456',
content='This is my reply to all',
reply_all=True,
@@ -718,13 +757,14 @@ def test_reply_to_email_all(outlook_toolkit, mock_graph_service):
mock_graph_service.me.messages.by_message_id().reply.post.assert_not_called()
-def test_reply_to_email_failure(outlook_toolkit, mock_graph_service):
+async def test_reply_to_email_failure(outlook_toolkit, mock_graph_service):
"""Test reply to email failure when using simple reply."""
mock_graph_service.me.messages.by_message_id().reply.post.side_effect = (
Exception("API Error: Unable to send reply")
)
- result = outlook_toolkit.outlook_reply_to_email(
+ result = await outlook_toolkit.outlook_reply_to_email(
message_id='msg123',
content='This reply will fail',
reply_all=False,
@@ -735,14 +775,15 @@ def test_reply_to_email_failure(outlook_toolkit, mock_graph_service):
assert 'API Error: Unable to send reply' in result['error']
-def test_reply_to_email_all_failure(outlook_toolkit, mock_graph_service):
+async def test_reply_to_email_all_failure(outlook_toolkit, mock_graph_service):
"""Test reply to email failure when using reply all."""
mock_reply_all = mock_graph_service.me.messages.by_message_id().reply_all
mock_reply_all.post.side_effect = Exception(
"API Error: Unable to send reply all"
)
- result = outlook_toolkit.outlook_reply_to_email(
+ result = await outlook_toolkit.outlook_reply_to_email(
message_id='msg456',
content='This reply all will fail',
reply_all=True,
@@ -753,12 +794,13 @@ def test_reply_to_email_all_failure(outlook_toolkit, mock_graph_service):
assert 'API Error: Unable to send reply all' in result['error']
-def test_update_draft_message(outlook_toolkit, mock_graph_service):
+async def test_update_draft_message(outlook_toolkit, mock_graph_service):
"""Test updating a draft message with all parameters."""
mock_by_message_id = mock_graph_service.me.messages.by_message_id()
mock_by_message_id.patch.return_value = None
- result = outlook_toolkit.outlook_update_draft_message(
+ result = await outlook_toolkit.outlook_update_draft_message(
message_id='draft123',
subject='Updated Subject',
content='Updated content',
@@ -782,14 +824,15 @@ def test_update_draft_message(outlook_toolkit, mock_graph_service):
mock_by_message_id.patch.assert_called_once()
-def test_update_draft_message_subject_only(
+async def test_update_draft_message_subject_only(
outlook_toolkit, mock_graph_service
):
"""Test updating only the subject of a draft message."""
mock_by_message_id = mock_graph_service.me.messages.by_message_id()
mock_by_message_id.patch.return_value = None
- result = outlook_toolkit.outlook_update_draft_message(
+ result = await outlook_toolkit.outlook_update_draft_message(
message_id='draft456',
subject='New Subject Only',
)
@@ -803,14 +846,17 @@ def test_update_draft_message_subject_only(
mock_by_message_id.patch.assert_called_once()
-def test_update_draft_message_failure(outlook_toolkit, mock_graph_service):
+async def test_update_draft_message_failure(
+ outlook_toolkit, mock_graph_service
+):
"""Test update draft message failure."""
mock_by_message_id = mock_graph_service.me.messages.by_message_id()
mock_by_message_id.patch.side_effect = Exception(
"API Error: Unable to update draft"
)
- result = outlook_toolkit.outlook_update_draft_message(
+ result = await outlook_toolkit.outlook_update_draft_message(
message_id='draft123',
subject='This update will fail',
)