44from unittest .mock import MagicMock , AsyncMock , patch
55import pytest
66from contextlib import contextmanager
7+
78# Mocking necessary modules and environment variables
89sys .modules ["azure.monitor.events.extension" ] = MagicMock ()
10+
911# Mocking environment variables
1012os .environ ["COSMOSDB_ENDPOINT" ] = "https://mock-endpoint"
1113os .environ ["COSMOSDB_KEY" ] = "mock-key"
1416os .environ ["AZURE_OPENAI_DEPLOYMENT_NAME" ] = "mock-deployment-name"
1517os .environ ["AZURE_OPENAI_API_VERSION" ] = "2023-01-01"
1618os .environ ["AZURE_OPENAI_ENDPOINT" ] = "https://mock-openai-endpoint"
19+
1720# Importing the module to test
1821from src .backend .agents .base_agent import BaseAgent
19- from src .backend .models .messages import ActionRequest , Step , StepStatus , ActionResponse , AgentMessage
22+ from src .backend .models .messages import ActionRequest , Step , StepStatus
2023from autogen_core .base import AgentId
21- from autogen_core . components . models import AssistantMessage , UserMessage
24+
2225# Context manager for setting up mocks
2326@contextmanager
2427def mock_context ():
@@ -28,6 +31,8 @@ def mock_context():
2831 mock_context_var .get .return_value = mock_context_instance
2932 mock_context_instance .set .return_value = None
3033 yield mock_runtime
34+
35+
3136@pytest .fixture
3237def mock_dependencies ():
3338 model_client = MagicMock ()
@@ -40,6 +45,8 @@ def mock_dependencies():
4045 "tools" : tools ,
4146 "tool_agent_id" : tool_agent_id ,
4247 }
48+
49+
4350@pytest .fixture
4451def base_agent (mock_dependencies ):
4552 with mock_context ():
@@ -53,19 +60,24 @@ def base_agent(mock_dependencies):
5360 tool_agent_id = mock_dependencies ["tool_agent_id" ],
5461 system_message = "This is a system message." ,
5562 )
63+
64+
5665def test_save_state (base_agent , mock_dependencies ):
5766 mock_dependencies ["model_context" ].save_state = MagicMock (return_value = {"state_key" : "state_value" })
5867 state = base_agent .save_state ()
5968 assert state == {"memory" : {"state_key" : "state_value" }}
69+
70+
6071def test_load_state (base_agent , mock_dependencies ):
6172 mock_dependencies ["model_context" ].load_state = MagicMock ()
6273 state = {"memory" : {"state_key" : "state_value" }}
6374 base_agent .load_state (state )
6475 mock_dependencies ["model_context" ].load_state .assert_called_once_with ({"state_key" : "state_value" })
76+
77+
6578@pytest .mark .asyncio
6679async def test_handle_action_request_error (base_agent , mock_dependencies ):
6780 """Test handle_action_request when tool_agent_caller_loop raises an error."""
68- # Mocking a Step object
6981 step = Step (
7082 id = "step_1" ,
7183 status = StepStatus .approved ,
@@ -77,12 +89,10 @@ async def test_handle_action_request_error(base_agent, mock_dependencies):
7789 session_id = "session_id" ,
7890 user_id = "user_id" ,
7991 )
80- # Mocking the model context methods
8192 mock_dependencies ["model_context" ].get_step = AsyncMock (return_value = step )
8293 mock_dependencies ["model_context" ].add_item = AsyncMock ()
83- # Mock tool_agent_caller_loop to raise an exception
94+
8495 with patch ("src.backend.agents.base_agent.tool_agent_caller_loop" , AsyncMock (side_effect = Exception ("Mock error" ))):
85- # Define the ActionRequest message
8696 message = ActionRequest (
8797 step_id = "step_1" ,
8898 session_id = "test_session" ,
@@ -91,17 +101,14 @@ async def test_handle_action_request_error(base_agent, mock_dependencies):
91101 agent = "HumanAgent" ,
92102 )
93103 ctx = MagicMock ()
94- # Call handle_action_request and capture exception
95104 with pytest .raises (ValueError ) as excinfo :
96105 await base_agent .handle_action_request (message , ctx )
97- # Assert that the exception matches the expected ValueError
98- assert "Return type <class 'NoneType'> not in return types" in str (excinfo .value ), (
99- "Expected ValueError due to NoneType return, but got a different exception."
100- )
106+ assert "Return type <class 'NoneType'> not in return types" in str (excinfo .value )
107+
108+
101109@pytest .mark .asyncio
102110async def test_handle_action_request_success (base_agent , mock_dependencies ):
103111 """Test handle_action_request with a successful tool_agent_caller_loop."""
104- # Update Step with a valid agent enum value
105112 step = Step (
106113 id = "step_1" ,
107114 status = StepStatus .approved ,
@@ -116,9 +123,8 @@ async def test_handle_action_request_success(base_agent, mock_dependencies):
116123 mock_dependencies ["model_context" ].get_step = AsyncMock (return_value = step )
117124 mock_dependencies ["model_context" ].update_step = AsyncMock ()
118125 mock_dependencies ["model_context" ].add_item = AsyncMock ()
119- # Mock the tool_agent_caller_loop to return a result
126+
120127 with patch ("src.backend.agents.base_agent.tool_agent_caller_loop" , new = AsyncMock (return_value = [MagicMock (content = "result" )])):
121- # Mock the publish_message method to be awaitable
122128 base_agent ._runtime .publish_message = AsyncMock ()
123129 message = ActionRequest (
124130 step_id = "step_1" ,
@@ -128,19 +134,17 @@ async def test_handle_action_request_success(base_agent, mock_dependencies):
128134 agent = "HumanAgent"
129135 )
130136 ctx = MagicMock ()
131- # Call the method being tested
132137 response = await base_agent .handle_action_request (message , ctx )
133- # Assertions to ensure the response is correct
138+
134139 assert response .status == StepStatus .completed
135140 assert response .result == "result"
136- assert response .plan_id == "plan_id" # Validate plan_id
137- assert response .session_id == "test_session" # Validate session_id
138- # Ensure publish_message was called
141+ assert response .plan_id == "plan_id"
142+ assert response .session_id == "test_session"
143+
139144 base_agent ._runtime .publish_message .assert_awaited_once_with (
140145 response ,
141146 AgentId (type = "group_chat_manager" , key = "test_session" ),
142147 sender = base_agent .id ,
143148 cancellation_token = None
144149 )
145- # Ensure the step was updated
146- mock_dependencies ["model_context" ].update_step .assert_called_once_with (step )
150+ mock_dependencies ["model_context" ].update_step .assert_called_once_with (step )
0 commit comments