Refactor timeout mechanism to improve code quality and error handling

Co-Authored-By: Joe Moura <joao@crewai.com>
This commit is contained in:
Devin AI
2025-03-16 22:51:34 +00:00
parent 4487d2538a
commit 6fa8f3b73f
3 changed files with 182 additions and 99 deletions

View File

@@ -4,6 +4,7 @@ from unittest.mock import MagicMock, patch
import pytest
from crewai import Agent, Task
from crewai.utilities import AgentExecutionTimeoutError
def test_agent_max_execution_time():
@@ -54,8 +55,53 @@ def test_agent_max_execution_time():
execution_time = time.time() - start_time
assert execution_time <= 2.1, f"Execution took {execution_time:.2f} seconds, expected ~1 second"
# Check that the exception message mentions timeout
assert "timeout" in str(excinfo.value).lower() or "execution time" in str(excinfo.value).lower()
# Check that the exception message mentions timeout or execution time
error_message = str(excinfo.value).lower()
assert any(term in error_message for term in ["timeout", "execution time", "exceeded maximum"])
# Run the test function
test_timeout()
def test_agent_timeout_error_message():
"""Test that the timeout error message includes agent and task information."""
# Create an agent with a very short timeout
with patch('crewai.agent.Agent.create_agent_executor'):
agent = Agent(
role="Test Agent",
goal="Test timeout error messaging",
backstory="I am testing the timeout error messaging",
max_execution_time=1, # Short timeout
verbose=True
)
# Create a task
task = Task(
description="This task should timeout quickly",
expected_output="This should never be returned",
agent=agent
)
# Mock the agent_executor
mock_executor = MagicMock()
def side_effect(*args, **kwargs):
# Sleep to trigger timeout
time.sleep(2)
return {"output": "This should never be returned"}
mock_executor.invoke.side_effect = side_effect
mock_executor.tools_names = []
mock_executor.tools_description = []
# Replace the agent's executor
agent.agent_executor = mock_executor
# Execute the task and expect an exception
with patch('crewai.agent.crewai_event_bus'):
with pytest.raises(Exception) as excinfo:
agent.execute_task(task)
# Verify error message contains agent name and task description
error_message = str(excinfo.value).lower()
assert "test agent" in error_message or "agent: test agent" in error_message
assert "this task should timeout" in error_message or "task: this task should timeout" in error_message