"""Tests for app handler functions. This module tests the main handler functions used in the Gradio UI, particularly focusing on input collection and execution handling. """ import json from unittest.mock import patch import pytest # Import the function we're testing from app import handle_execute_plan from kg_services.ontology import MCPPrompt, MCPTool, PlannedStep class TestHandleExecutePlan: """Test suite for handle_execute_plan function.""" @pytest.fixture def sample_tool(self) -> MCPTool: """Create a sample MCPTool for testing.""" return MCPTool( tool_id="test-tool-001", name="Test Sentiment Analyzer", description="A test tool for sentiment analysis", tags=["sentiment", "analysis", "test"], invocation_command_stub="sentiment_analyze --input {text}", ) @pytest.fixture def sample_prompt(self) -> MCPPrompt: """Create a sample MCPPrompt for testing.""" return MCPPrompt( prompt_id="test-prompt-001", name="Basic Sentiment Analysis", description="Analyze sentiment of provided text", target_tool_id="test-tool-001", template_string="Analyze the sentiment of this text: {{text_input}}", input_variables=["text_input"], difficulty_level="beginner", example_inputs={"text_input": "This is a great product!"}, ) @pytest.fixture def sample_planned_step( self, sample_tool: MCPTool, sample_prompt: MCPPrompt ) -> PlannedStep: """Create a sample PlannedStep for testing.""" return PlannedStep(tool=sample_tool, prompt=sample_prompt, relevance_score=0.95) @pytest.fixture def multi_input_prompt(self) -> MCPPrompt: """Create a prompt with multiple input variables.""" return MCPPrompt( prompt_id="test-prompt-multi", name="Multi-Input Analysis", description="Analysis with multiple inputs", target_tool_id="test-tool-001", template_string="Analyze {{input1}} with context {{input2}} and format {{input3}}", input_variables=["input1", "input2", "input3"], difficulty_level="intermediate", ) @pytest.fixture def no_input_prompt(self) -> MCPPrompt: """Create a prompt with no input variables.""" return MCPPrompt( prompt_id="test-prompt-no-input", name="No Input Required", description="A prompt that requires no inputs", target_tool_id="test-tool-001", template_string="Perform standard analysis", input_variables=[], difficulty_level="beginner", ) @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_basic_success( self, mock_planner_agent, mock_executor_agent, sample_planned_step ): """Test successful input collection with single variable.""" # Arrange mock_planner_agent.generate_plan.return_value = [sample_planned_step] mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_success", "execution_id": "exec_test_123", "tool_information": {"tool_name": "Test Sentiment Analyzer"}, "prompt_information": {"prompt_name": "Basic Sentiment Analysis"}, "execution_details": {"inputs_count": 1, "execution_time_ms": 1250}, "results": { "mock_output": "Mock analysis results", "confidence_score": 0.95, }, "metadata": {"simulation_version": "MVP3_Sprint4"}, } test_query = "analyze sentiment" test_input = "This is a great product!" # Act result = handle_execute_plan(test_query, test_input) # Assert assert "šŸŽ‰ **Execution Complete!**" in result assert "Test Sentiment Analyzer" in result assert "Basic Sentiment Analysis" in result assert test_input in result assert "āœ…" in result # Verify planner was called correctly mock_planner_agent.generate_plan.assert_called_once_with(test_query, top_k=1) # Verify executor was called mock_executor_agent.execute_plan_step.assert_called_once() @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_multiple_inputs( self, mock_planner_agent, mock_executor_agent, sample_tool, multi_input_prompt ): """Test input collection with multiple variables.""" # Arrange planned_step = PlannedStep( tool=sample_tool, prompt=multi_input_prompt, relevance_score=0.88 ) mock_planner_agent.generate_plan.return_value = [planned_step] mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_success", "execution_id": "exec_test_456", "tool_information": {"tool_name": "Test Tool"}, "prompt_information": {"prompt_name": "Multi Input Prompt"}, "execution_details": {"inputs_count": 3, "execution_time_ms": 1250}, "results": { "mock_output": "Mock analysis results", "confidence_score": 0.95, }, "metadata": {"simulation_version": "MVP3_Sprint4"}, } test_query = "complex analysis" input1, input2, input3 = "data1", "context2", "format3" # Act result = handle_execute_plan( test_query, input1, input2, input3, "unused4", "unused5" ) # Assert assert "šŸŽ‰ **Execution Complete!**" in result assert input1 in result assert input2 in result assert input3 in result # Parse the JSON section to verify correct mapping json_start = result.find("```json\n") if json_start != -1: json_start += 8 json_end = result.find("\n```", json_start) if json_end != -1: json_content = result[json_start:json_end].strip() if json_content: parsed_inputs = json.loads(json_content) assert parsed_inputs == {"input1": input1, "input2": input2, "input3": input3} else: # If JSON content is empty, just verify the inputs are present in the result assert all(inp in result for inp in [input1, input2, input3]) else: # If JSON section not properly closed, just verify inputs are present assert all(inp in result for inp in [input1, input2, input3]) else: # If no JSON section found, just verify inputs are present in the result assert all(inp in result for inp in [input1, input2, input3]) @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_no_inputs_required( self, mock_planner_agent, mock_executor_agent, sample_tool, no_input_prompt ): """Test handling of prompts that require no inputs.""" # Arrange planned_step = PlannedStep( tool=sample_tool, prompt=no_input_prompt, relevance_score=0.90 ) mock_planner_agent.generate_plan.return_value = [planned_step] mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_success", "execution_id": "exec_test_789", "tool_information": {"tool_name": "Test Tool"}, "prompt_information": {"prompt_name": "No Input Prompt"}, "execution_details": {"inputs_count": 0, "execution_time_ms": 1250}, "results": { "mock_output": "Mock analysis results", "confidence_score": 0.95, }, "metadata": {"simulation_version": "MVP3_Sprint4"}, } test_query = "standard analysis" # Act result = handle_execute_plan(test_query, "unused1", "unused2") # Assert assert "šŸŽ‰ **Execution Complete!**" in result assert "No Input Required" in result # Verify empty inputs dict json_start = result.find("```json\n") if json_start != -1: json_start += 8 json_end = result.find("\n```", json_start) if json_end != -1: json_content = result[json_start:json_end].strip() if json_content: parsed_inputs = json.loads(json_content) assert parsed_inputs == {} # If JSON content is empty, that's acceptable for no inputs required def test_handle_execute_plan_no_planner_agent(self): """Test error handling when planner agent is not available.""" # Act with patch("app.planner_agent", None): result = handle_execute_plan("test query", "input1") # Assert assert "āŒ **Error**: Planner service not available" in result @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_empty_query(self, mock_planner_agent, mock_executor_agent): """Test error handling with empty query.""" # Act result = handle_execute_plan("", "input1") # Assert assert "āŒ **Error**: Original query is missing" in result @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_no_planned_steps(self, mock_planner_agent, mock_executor_agent): """Test error handling when no planned steps are returned.""" # Arrange mock_planner_agent.generate_plan.return_value = [] # Act result = handle_execute_plan("test query", "input1") # Assert assert "āŒ **Error**: Could not retrieve the current action plan" in result @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_planner_exception(self, mock_planner_agent, mock_executor_agent): """Test error handling when planner raises an exception.""" # Arrange mock_planner_agent.generate_plan.side_effect = Exception("Planner error") # Act result = handle_execute_plan("test query", "input1") # Assert assert "āŒ **Execution Error**" in result assert "Planner error" in result @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_partial_inputs( self, mock_planner_agent, mock_executor_agent, sample_tool, multi_input_prompt ): """Test handling when fewer inputs are provided than required.""" # Arrange planned_step = PlannedStep( tool=sample_tool, prompt=multi_input_prompt, relevance_score=0.75 ) mock_planner_agent.generate_plan.return_value = [planned_step] mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_success", "execution_id": "exec_test_partial", "tool_information": {"tool_name": "Test Tool"}, "prompt_information": {"prompt_name": "Multi Input Prompt"}, "execution_details": {"inputs_count": 2, "execution_time_ms": 1250}, "results": { "mock_output": "Mock analysis results", "confidence_score": 0.95, }, "metadata": {"simulation_version": "MVP3_Sprint4"}, } test_query = "partial input test" # Only provide 2 inputs for a 3-input prompt input1, input2 = "data1", "context2" # Act result = handle_execute_plan(test_query, input1, input2) # Assert assert "šŸŽ‰ **Execution Complete!**" in result # Parse JSON to verify partial input handling json_start = result.find("```json\n") if json_start != -1: json_start += 8 json_end = result.find("\n```", json_start) if json_end != -1: json_content = result[json_start:json_end].strip() if json_content: parsed_inputs = json.loads(json_content) # Should have empty string for missing input expected = {"input1": input1, "input2": input2, "input3": ""} assert parsed_inputs == expected else: # If JSON content is empty, just verify provided inputs are in the result assert input1 in result and input2 in result else: # If JSON section not properly closed, just verify provided inputs are present assert input1 in result and input2 in result else: # If no JSON section found, just verify provided inputs are present in the result assert input1 in result and input2 in result @patch("app.executor_agent") @patch("app.planner_agent") @patch("app.logger") def test_handle_execute_plan_logging( self, mock_logger, mock_planner_agent, mock_executor_agent, sample_planned_step ): """Test that appropriate logging occurs during execution.""" # Arrange mock_planner_agent.generate_plan.return_value = [sample_planned_step] mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_success", "execution_id": "exec_test_log", "tool_information": {"tool_name": "Test Sentiment Analyzer"}, "prompt_information": {"prompt_name": "Basic Sentiment Analysis"}, "execution_details": {"inputs_count": 1, "execution_time_ms": 1250}, "results": { "mock_output": "Mock analysis results", "confidence_score": 0.95, }, "metadata": {"simulation_version": "MVP3_Sprint4"}, } test_query = "logging test" test_input = "test input" # Act handle_execute_plan(test_query, test_input) # Assert # Check that info logs were called assert mock_logger.info.call_count >= 2 # Verify specific log messages log_calls = [call[0][0] for call in mock_logger.info.call_args_list] assert any("Executing plan with StubExecutorAgent" in log for log in log_calls) assert any( "Execution simulation completed successfully" in log for log in log_calls ) @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_json_formatting( self, mock_planner_agent, mock_executor_agent, sample_planned_step ): """Test that JSON formatting in output is valid.""" # Arrange mock_planner_agent.generate_plan.return_value = [sample_planned_step] mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_success", "execution_id": "exec_test_json", "tool_information": {"tool_name": "Test Sentiment Analyzer"}, "prompt_information": {"prompt_name": "Basic Sentiment Analysis"}, "execution_details": {"inputs_count": 1, "execution_time_ms": 1250}, "results": { "mock_output": "Mock analysis results", "confidence_score": 0.95, }, "metadata": {"simulation_version": "MVP3_Sprint4"}, } test_query = "json formatting test" test_input = "test input with special chars: @#$%^&*()" # Act result = handle_execute_plan(test_query, test_input) # Assert # Verify the input is properly displayed in the output assert "šŸŽ‰ **Execution Complete!**" in result assert test_input in result assert "Mock analysis results" in result # Verify special characters are handled properly assert "@#$%^&*()" in result @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_markdown_formatting( self, mock_planner_agent, mock_executor_agent, sample_planned_step ): """Test that execution results are properly formatted in Markdown.""" # Arrange mock_planner_agent.generate_plan.return_value = [sample_planned_step] mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_success", "execution_id": "exec_test_md", "tool_information": {"tool_name": "Test Sentiment Analyzer"}, "prompt_information": {"prompt_name": "Basic Sentiment Analysis"}, "execution_details": {"inputs_count": 1, "execution_time_ms": 1250}, "results": { "mock_output": "Mock analysis results", "confidence_score": 0.95, }, "metadata": {"simulation_version": "MVP3_Sprint4"}, } test_query = "markdown test" test_input = "test input" # Act result = handle_execute_plan(test_query, test_input) # Assert # Check for Markdown headers assert "# šŸŽ‰ **Execution Complete!**" in result assert "## šŸ“Š **Execution Summary**" in result assert "## šŸ”§ **Tool & Prompt Information**" in result assert "## šŸ“ **Input Summary**" in result assert "## šŸŽÆ **Execution Results**" in result # Check for proper formatting elements assert "- **Status**: āœ…" in result assert "- **Tool**:" in result assert "Mock analysis results" in result class TestErrorHandling: """Test suite for error handling in app handlers.""" @pytest.fixture def sample_tool(self) -> MCPTool: """Create a sample MCPTool for testing.""" return MCPTool( tool_id="test-tool-error", name="Test Error Tool", description="A tool for testing error scenarios", tags=["test", "error"], invocation_command_stub="test_error {input}", ) @pytest.fixture def sample_prompt(self) -> MCPPrompt: """Create a sample MCPPrompt for testing.""" return MCPPrompt( prompt_id="test-prompt-error", name="Test Error Prompt", description="A prompt for testing error scenarios", target_tool_id="test-tool-error", template_string="Process: {{text_input}}", input_variables=["text_input"], difficulty_level="beginner", ) @pytest.fixture def sample_planned_step( self, sample_tool: MCPTool, sample_prompt: MCPPrompt ) -> PlannedStep: """Create a sample PlannedStep for testing.""" return PlannedStep(tool=sample_tool, prompt=sample_prompt, relevance_score=0.95) @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_error_response( self, mock_planner_agent, mock_executor_agent, sample_planned_step ): """Test handling of error responses from executor.""" # Arrange mock_planner_agent.generate_plan.return_value = [sample_planned_step] mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_error", "execution_id": "exec_err_test_123", "tool_information": {"tool_name": "Test Error Tool"}, "prompt_information": {"prompt_name": "Test Error Prompt"}, "execution_details": { "inputs_count": 1, "execution_time_ms": 500, "error_occurred_at": 45, }, "error_information": { "error_type": "user_requested", "error_code": "USR_REQ_001", "error_severity": "medium", "error_message": "User explicitly requested error simulation", "error_details": "Error simulation was triggered by user input containing error keywords", "suggested_fixes": [ "Remove error keywords from input", "Use different test data", ], "retry_recommended": True, }, "results": { "message": "Tool execution failed: User explicitly requested error simulation", "mock_output": "**Error Simulation Activated**\n\nāŒ **User-Requested Error**\nThis error was triggered because your input contained error simulation keywords.", "confidence_score": 0.0, }, "metadata": { "simulation_version": "MVP3_Sprint4", "error_simulation": "user_requested", "trigger_info": "This should fail and show an error", }, } test_query = "error test" test_input = "This should fail and show an error" # Act result = handle_execute_plan(test_query, test_input) # Assert assert "# āŒ **Execution Failed!**" in result assert "## 🚨 **Error Summary**" in result assert "- **Status**: āŒ Simulated Error" in result assert "- **Type**: user requested" in result assert "## āš ļø **Error Details**" in result assert "## šŸ’” **Recovery Suggestions**" in result assert "Remove error keywords from input" in result assert "Use different test data" in result assert "- **Retry Recommended**: āœ… Yes" in result @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_security_error( self, mock_planner_agent, mock_executor_agent, sample_planned_step ): """Test handling of security violation errors.""" # Arrange mock_planner_agent.generate_plan.return_value = [sample_planned_step] mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_error", "execution_id": "exec_err_sec_456", "tool_information": {"tool_name": "Test Error Tool"}, "prompt_information": {"prompt_name": "Test Error Prompt"}, "execution_details": { "inputs_count": 1, "execution_time_ms": 250, "error_occurred_at": 15, }, "error_information": { "error_type": "security_violation", "error_code": "SEC_001", "error_severity": "high", "error_message": "Potential security violation detected", "error_details": "Input contains suspicious content that may pose security risks", "suggested_fixes": [ "Remove suspicious code/scripts from input", "Use plain text input only", ], "retry_recommended": False, }, "results": { "message": "Tool execution failed: Potential security violation detected", "mock_output": "**Security Error**\n\nšŸ›”ļø **Security Violation Detected**\nThe input contains content that may pose security risks.", "confidence_score": 0.0, }, "metadata": { "simulation_version": "MVP3_Sprint4", "error_simulation": "security_violation", "trigger_info": "suspicious_content", }, } test_query = "security test" test_input = "Process this content" # Act result = handle_execute_plan(test_query, test_input) # Assert assert "# āŒ **Execution Failed!**" in result assert "- **Type**: security violation" in result assert "- **Retry Recommended**: āŒ No" in result assert "Security Violation Detected" in result assert "Remove suspicious code/scripts from input" in result @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_network_timeout_error( self, mock_planner_agent, mock_executor_agent, sample_planned_step ): """Test handling of network timeout errors.""" # Arrange mock_planner_agent.generate_plan.return_value = [sample_planned_step] mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_error", "execution_id": "exec_err_net_789", "tool_information": {"tool_name": "Test Error Tool"}, "prompt_information": {"prompt_name": "Test Error Prompt"}, "execution_details": { "inputs_count": 1, "execution_time_ms": 800, "error_occurred_at": 75, }, "error_information": { "error_type": "network_timeout", "error_code": "NET_001", "error_severity": "medium", "error_message": "Network request timed out", "error_details": "The tool failed to complete processing within the allowed time limit", "suggested_fixes": [ "Retry the operation", "Check network connectivity", "Try with smaller input", ], "retry_recommended": True, }, "results": { "message": "Tool execution failed: Network request timed out", "mock_output": "**Network Timeout**\n\nā° **Operation Timed Out**\nThe request took too long to process and was automatically cancelled.", "confidence_score": 0.0, }, "metadata": { "simulation_version": "MVP3_Sprint4", "error_simulation": "network_timeout", "trigger_info": "random", }, } test_query = "network timeout test" test_input = "normal input" # Act result = handle_execute_plan(test_query, test_input) # Assert assert "# āŒ **Execution Failed!**" in result assert "- **Type**: network timeout" in result assert "Operation Timed Out" in result assert "Retry the operation" in result @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_error_markdown_structure( self, mock_planner_agent, mock_executor_agent, sample_planned_step ): """Test that error responses maintain proper Markdown structure.""" # Arrange mock_planner_agent.generate_plan.return_value = [sample_planned_step] mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_error", "execution_id": "exec_err_md_test", "tool_information": {"tool_name": "Test Error Tool"}, "prompt_information": {"prompt_name": "Test Error Prompt"}, "execution_details": { "inputs_count": 1, "execution_time_ms": 300, "error_occurred_at": 30, }, "error_information": { "error_type": "input_too_large", "error_code": "VAL_001", "error_severity": "medium", "error_message": "Input exceeds maximum allowed size", "error_details": "Input size limit exceeded", "suggested_fixes": [ "Reduce input size", "Split large inputs into smaller chunks", ], "retry_recommended": True, }, "results": { "message": "Tool execution failed: Input exceeds maximum allowed size", "mock_output": "**Input Size Error**\n\nšŸ“ **Input Too Large**\nThe provided input exceeds the maximum allowed size for this tool.", "confidence_score": 0.0, }, "metadata": { "simulation_version": "MVP3_Sprint4", "error_simulation": "input_too_large", "trigger_info": "large_input", }, } test_query = "markdown structure test" test_input = "test input" # Act result = handle_execute_plan(test_query, test_input) # Assert - Check for proper Markdown headers in error response assert result.startswith("# āŒ **Execution Failed!**") assert "## 🚨 **Error Summary**" in result assert "## šŸ”§ **Tool & Prompt Information**" in result assert "## āš ļø **Error Details**" in result assert "## šŸ’” **Recovery Suggestions**" in result assert "## šŸ“ **Input Summary**" in result assert "## šŸ“„ **Error Output**" in result # Check for proper list formatting assert "1. Reduce input size" in result assert "2. Split large inputs into smaller chunks" in result # Check for proper formatting assert "---" in result # Separator line @patch("app.executor_agent") @patch("app.planner_agent") def test_handle_execute_plan_error_vs_success_distinction( self, mock_planner_agent, mock_executor_agent, sample_planned_step ): """Test that error and success responses are clearly distinguished.""" # Test error response first mock_planner_agent.generate_plan.return_value = [sample_planned_step] mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_error", "execution_id": "exec_err_test", "tool_information": {"tool_name": "Test Tool"}, "prompt_information": {"prompt_name": "Test Prompt"}, "execution_details": {"inputs_count": 1, "execution_time_ms": 300}, "error_information": { "error_type": "test_scenario", "error_code": "TST_ERR_001", "error_severity": "high", "error_message": "Test error scenario activated", "error_details": "Test error details", "suggested_fixes": ["This is for testing"], "retry_recommended": True, }, "results": {"mock_output": "Error output", "confidence_score": 0.0}, "metadata": { "simulation_version": "MVP3_Sprint4", "error_simulation": "test_scenario", }, } # Act error_result = handle_execute_plan("error test", "test error") # Assert error response characteristics assert "āŒ **Execution Failed!**" in error_result assert "🚨 **Error Summary**" in error_result assert "āš ļø **Error Details**" in error_result assert "šŸ“„ **Error Output**" in error_result assert "šŸŽ‰ **Execution Complete!**" not in error_result assert ( "- **Status**: āœ…" not in error_result ) # Status should not show success checkmark # Now test success response mock_executor_agent.execute_plan_step.return_value = { "status": "simulated_success", "execution_id": "exec_success_test", "tool_information": {"tool_name": "Test Tool"}, "prompt_information": {"prompt_name": "Test Prompt"}, "execution_details": {"inputs_count": 1, "execution_time_ms": 1500}, "results": {"mock_output": "Success output", "confidence_score": 0.95}, "metadata": { "simulation_version": "MVP3_Sprint4", "error_simulation": "none", }, } # Act success_result = handle_execute_plan("success test", "normal input") # Assert success response characteristics assert "šŸŽ‰ **Execution Complete!**" in success_result assert "šŸ“Š **Execution Summary**" in success_result assert "šŸŽÆ **Execution Results**" in success_result assert "āŒ **Execution Failed!**" not in success_result assert "🚨 **Error Summary**" not in success_result