Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /autonomous /tests /smart /test_agent.py
| """ | |
| Smart Tests for agent.py | |
| Agent: #025 | |
| Module: agent.py | |
| Pattern: TOOLEXECUTOR, GOLDEN FILES, COMMANDRUNNER | |
| """ | |
| import asyncio | |
| from dataclasses import dataclass | |
| from datetime import datetime | |
| from unittest.mock import AsyncMock, MagicMock, Mock, patch | |
| import pytest | |
| # Import module under test | |
| from autonomous import agent | |
| from autonomous.agent import AgentConfig, AutonomousAgent | |
| from autonomous.memory import MemoryManager | |
| from autonomous.react import ReActLoop | |
| from autonomous.tool_executor import SafetyLevel, ToolExecutor | |
| # ============================================================================= | |
| # FIXTURES | |
| # ============================================================================= | |
| def mock_llm_client(): | |
| """Create mock LLM client.""" | |
| client = MagicMock() | |
| client.generate = AsyncMock(return_value="Thought: I should scan the target\nAction: nmap -sS target") | |
| return client | |
| def agent_config(): | |
| """Create AgentConfig instance.""" | |
| return AgentConfig( | |
| max_iterations=10, | |
| safety_level=SafetyLevel.NON_DESTRUCTIVE, | |
| human_in_the_loop=False, | |
| enable_memory=True, | |
| ) | |
| def autonomous_agent(mock_llm_client, agent_config): | |
| """Create AutonomousAgent instance.""" | |
| with ( | |
| patch("autonomous.agent.MemoryManager") as mock_mem, | |
| patch("autonomous.agent.ReActLoop") as mock_react, | |
| patch("autonomous.agent.ToolExecutor") as mock_tools, | |
| ): | |
| mock_mem.return_value = MagicMock() | |
| mock_mem.return_value.record_episode = AsyncMock() | |
| mock_react.return_value = MagicMock() | |
| mock_react.return_value.run = AsyncMock( | |
| return_value={ | |
| "goal": "Test goal", | |
| "completed": True, | |
| "steps_taken": 3, | |
| "history": [], | |
| } | |
| ) | |
| mock_tools.return_value = MagicMock() | |
| mock_tools.return_value.get_available_tools = MagicMock(return_value=[]) | |
| agent = AutonomousAgent(llm_client=mock_llm_client, config=agent_config) | |
| yield agent | |
| def mock_react_result(): | |
| """Create mock ReAct loop result.""" | |
| return { | |
| "goal": "Find vulnerabilities", | |
| "completed": True, | |
| "steps_taken": 3, | |
| "history": [ | |
| {"type": "action", "tool": "nmap"}, | |
| { | |
| "type": "observation", | |
| "result": {"findings": [{"type": "open_port"}]}, | |
| }, | |
| {"type": "action", "tool": "nuclei"}, | |
| { | |
| "type": "observation", | |
| "result": {"open_ports": [{"port": "80"}]}, | |
| }, | |
| ], | |
| } | |
| # ============================================================================= | |
| # TEST 1: Module Import | |
| # ============================================================================= | |
| def test_module_importable(): | |
| """Test that agent module can be imported.""" | |
| assert agent is not None | |
| assert hasattr(agent, "AutonomousAgent") | |
| assert hasattr(agent, "AgentConfig") | |
| # ============================================================================= | |
| # TEST 2: ToolExecutor Pattern | |
| # ============================================================================= | |
| def test_module_uses_tool_executor(mock_llm_client): | |
| """Test that module follows ToolExecutor pattern.""" | |
| with ( | |
| patch("autonomous.agent.ToolExecutor") as mock_tools, | |
| patch("autonomous.agent.MemoryManager"), | |
| patch("autonomous.agent.ReActLoop"), | |
| ): | |
| mock_tools.return_value = MagicMock() | |
| config = AgentConfig(safety_level=SafetyLevel.READ_ONLY) | |
| agent = AutonomousAgent(llm_client=mock_llm_client, config=config) | |
| # Verify ToolExecutor was created with correct safety level | |
| mock_tools.assert_called_once() | |
| call_kwargs = mock_tools.call_args.kwargs | |
| assert call_kwargs.get("safety_level") == SafetyLevel.READ_ONLY | |
| # ============================================================================= | |
| # TEST 3: NOT_FOUND Error Handling | |
| # ============================================================================= | |
| async def test_module_not_found_error(mock_llm_client): | |
| """Test handling when required components are not found.""" | |
| with ( | |
| patch("autonomous.agent.ReActLoop") as mock_react, | |
| patch("autonomous.agent.MemoryManager"), | |
| patch("autonomous.agent.ToolExecutor"), | |
| ): | |
| mock_react.return_value = MagicMock() | |
| mock_react.return_value.run = AsyncMock(side_effect=ModuleNotFoundError("Module not found")) | |
| agent = AutonomousAgent(llm_client=mock_llm_client) | |
| with pytest.raises(ModuleNotFoundError): | |
| await agent.run(goal="Test goal") | |
| # ============================================================================= | |
| # TEST 4: TIMEOUT Error Handling | |
| # ============================================================================= | |
| async def test_module_timeout_error(mock_llm_client): | |
| """Test handling of timeout errors.""" | |
| with ( | |
| patch("autonomous.agent.ReActLoop") as mock_react, | |
| patch("autonomous.agent.MemoryManager"), | |
| patch("autonomous.agent.ToolExecutor"), | |
| ): | |
| mock_react.return_value = MagicMock() | |
| mock_react.return_value.run = AsyncMock(side_effect=asyncio.TimeoutError("Execution timeout")) | |
| agent = AutonomousAgent(llm_client=mock_llm_client) | |
| with pytest.raises(asyncio.TimeoutError): | |
| await agent.run(goal="Test goal") | |
| # ============================================================================= | |
| # TEST 5: Parser Extracts Findings | |
| # ============================================================================= | |
| async def test_module_parser_extracts_findings(mock_llm_client, mock_react_result): | |
| """Test that findings are correctly extracted from execution.""" | |
| with ( | |
| patch("autonomous.agent.ReActLoop") as mock_react, | |
| patch("autonomous.agent.MemoryManager") as mock_mem, | |
| patch("autonomous.agent.ToolExecutor") as mock_tools, | |
| ): | |
| mock_react.return_value = MagicMock() | |
| mock_react.return_value.run = AsyncMock(return_value=mock_react_result) | |
| mock_mem.return_value = MagicMock() | |
| mock_mem.return_value.record_episode = AsyncMock() | |
| mock_tools.return_value = MagicMock() | |
| mock_tools.return_value.get_available_tools = MagicMock(return_value=[]) | |
| agent = AutonomousAgent(llm_client=mock_llm_client) | |
| result = await agent.run(goal="Find vulnerabilities") | |
| assert "findings" in result | |
| assert len(result["findings"]) > 0 | |
| assert result["summary"]["findings_count"] > 0 | |
| # ============================================================================= | |
| # TEST 6: End-to-End with Mock | |
| # ============================================================================= | |
| async def test_module_end_to_end_mocked(mock_llm_client): | |
| """Test full workflow with mocked components.""" | |
| with ( | |
| patch("autonomous.agent.ReActLoop") as mock_react, | |
| patch("autonomous.agent.MemoryManager") as mock_mem, | |
| patch("autonomous.agent.ToolExecutor") as mock_tools, | |
| ): | |
| mock_react.return_value = MagicMock() | |
| mock_react.return_value.run = AsyncMock( | |
| return_value={ | |
| "goal": "Test goal", | |
| "completed": True, | |
| "steps_taken": 5, | |
| "history": [], | |
| } | |
| ) | |
| mock_mem.return_value = MagicMock() | |
| mock_mem.return_value.record_episode = AsyncMock() | |
| mock_tools.return_value = MagicMock() | |
| mock_tools.return_value.get_available_tools = MagicMock(return_value=[{"name": "nmap", "description": "Port scanner"}]) | |
| agent = AutonomousAgent(llm_client=mock_llm_client) | |
| result = await agent.run(goal="Test goal", target="example.com") | |
| assert "summary" in result | |
| assert result["summary"]["goal"] == "Test goal" | |
| assert result["summary"]["target"] == "example.com" | |
| assert result["summary"]["completed"] is True | |
| assert "timestamp" in result | |
| assert "agent_version" in result | |
| async def test_module_scan_target(mock_llm_client): | |
| """Test scan_target convenience method.""" | |
| with ( | |
| patch("autonomous.agent.ReActLoop") as mock_react, | |
| patch("autonomous.agent.MemoryManager") as mock_mem, | |
| patch("autonomous.agent.ToolExecutor") as mock_tools, | |
| ): | |
| mock_react.return_value = MagicMock() | |
| mock_react.return_value.run = AsyncMock( | |
| return_value={ | |
| "goal": "Quick reconnaissance of example.com", | |
| "completed": True, | |
| "steps_taken": 3, | |
| "history": [], | |
| } | |
| ) | |
| mock_mem.return_value = MagicMock() | |
| mock_mem.return_value.record_episode = AsyncMock() | |
| mock_tools.return_value = MagicMock() | |
| mock_tools.return_value.get_available_tools = MagicMock(return_value=[]) | |
| agent = AutonomousAgent(llm_client=mock_llm_client) | |
| result = await agent.scan_target("example.com", scan_type="quick") | |
| assert "summary" in result | |
| mock_react.return_value.run.assert_called_once() | |
| # ============================================================================= | |
| # TEST 7: Empty Input Handling | |
| # ============================================================================= | |
| async def test_module_empty_input(mock_llm_client): | |
| """Test handling of empty input.""" | |
| with ( | |
| patch("autonomous.agent.ReActLoop") as mock_react, | |
| patch("autonomous.agent.MemoryManager") as mock_mem, | |
| patch("autonomous.agent.ToolExecutor") as mock_tools, | |
| ): | |
| mock_react.return_value = MagicMock() | |
| mock_react.return_value.run = AsyncMock( | |
| return_value={ | |
| "goal": "", | |
| "completed": True, | |
| "steps_taken": 0, | |
| "history": [], | |
| } | |
| ) | |
| mock_mem.return_value = MagicMock() | |
| mock_mem.return_value.record_episode = AsyncMock() | |
| mock_tools.return_value = MagicMock() | |
| mock_tools.return_value.get_available_tools = MagicMock(return_value=[]) | |
| agent = AutonomousAgent(llm_client=mock_llm_client) | |
| result = await agent.run(goal="") | |
| assert "summary" in result | |
| assert result["summary"]["findings_count"] == 0 | |
| async def test_module_empty_history(mock_llm_client): | |
| """Test handling of empty history.""" | |
| with ( | |
| patch("autonomous.agent.ReActLoop") as mock_react, | |
| patch("autonomous.agent.MemoryManager") as mock_mem, | |
| patch("autonomous.agent.ToolExecutor") as mock_tools, | |
| ): | |
| mock_react.return_value = MagicMock() | |
| mock_react.return_value.run = AsyncMock( | |
| return_value={ | |
| "goal": "Test", | |
| "completed": True, | |
| "steps_taken": 0, | |
| "history": [], | |
| } | |
| ) | |
| mock_mem.return_value = MagicMock() | |
| mock_mem.return_value.record_episode = AsyncMock() | |
| mock_tools.return_value = MagicMock() | |
| mock_tools.return_value.get_available_tools = MagicMock(return_value=[]) | |
| agent = AutonomousAgent(llm_client=mock_llm_client) | |
| result = await agent.run(goal="Test") | |
| assert result["summary"]["duration"] == 0.0 | |
| assert result["summary"]["tools_used"] == [] | |
| # ============================================================================= | |
| # TEST 8: Invalid Output Handling | |
| # ============================================================================= | |
| async def test_module_invalid_output(mock_llm_client): | |
| """Test handling of invalid/malformed output.""" | |
| with ( | |
| patch("autonomous.agent.ReActLoop") as mock_react, | |
| patch("autonomous.agent.MemoryManager") as mock_mem, | |
| patch("autonomous.agent.ToolExecutor") as mock_tools, | |
| ): | |
| mock_react.return_value = MagicMock() | |
| mock_react.return_value.run = AsyncMock( | |
| return_value={ | |
| "goal": "Test", | |
| "completed": True, | |
| "steps_taken": 2, | |
| "history": [ | |
| { | |
| "type": "observation", | |
| "result": "invalid_result", | |
| }, # Not a dict | |
| {"type": "observation", "result": {"unknown_field": []}}, | |
| ], | |
| } | |
| ) | |
| mock_mem.return_value = MagicMock() | |
| mock_mem.return_value.record_episode = AsyncMock() | |
| mock_tools.return_value = MagicMock() | |
| mock_tools.return_value.get_available_tools = MagicMock(return_value=[]) | |
| agent = AutonomousAgent(llm_client=mock_llm_client) | |
| result = await agent.run(goal="Test") | |
| # Should not crash, findings should be empty | |
| assert "findings" in result | |
| async def test_module_exploit_safety_check(mock_llm_client): | |
| """Test that exploitation requires proper safety level.""" | |
| with ( | |
| patch("autonomous.agent.ReActLoop"), | |
| patch("autonomous.agent.MemoryManager"), | |
| patch("autonomous.agent.ToolExecutor"), | |
| ): | |
| # Create agent with NON_DESTRUCTIVE level (too low for exploit) | |
| config = AgentConfig(safety_level=SafetyLevel.NON_DESTRUCTIVE) | |
| agent = AutonomousAgent(llm_client=mock_llm_client, config=config) | |
| result = await agent.exploit_target("example.com", "RCE") | |
| assert "error" in result | |
| assert "safety" in result["error"].lower() | |
| assert result["required"] == SafetyLevel.EXPLOIT.name | |
| # ============================================================================= | |
| # ADDITIONAL TESTS FOR AGENTCONFIG | |
| # ============================================================================= | |
| def test_agent_config_defaults(): | |
| """Test AgentConfig default values.""" | |
| config = AgentConfig() | |
| assert config.max_iterations == 50 | |
| assert config.safety_level == SafetyLevel.NON_DESTRUCTIVE | |
| assert config.human_in_the_loop is False | |
| assert config.enable_memory is True | |
| assert config.use_docker is False | |
| assert config.timeout == 300 | |
| def test_agent_config_custom(): | |
| """Test AgentConfig with custom values.""" | |
| config = AgentConfig( | |
| max_iterations=100, | |
| safety_level=SafetyLevel.EXPLOIT, | |
| human_in_the_loop=True, | |
| enable_memory=False, | |
| ) | |
| assert config.max_iterations == 100 | |
| assert config.safety_level == SafetyLevel.EXPLOIT | |
| assert config.human_in_the_loop is True | |
| assert config.enable_memory is False | |
| # ============================================================================= | |
| # ADDITIONAL TESTS FOR AUTONOMOUSAGENT | |
| # ============================================================================= | |
| def test_agent_get_capabilities(mock_llm_client): | |
| """Test get_capabilities method.""" | |
| with ( | |
| patch("autonomous.agent.ToolExecutor") as mock_tools, | |
| patch("autonomous.agent.MemoryManager"), | |
| patch("autonomous.agent.ReActLoop"), | |
| ): | |
| mock_tools.return_value = MagicMock() | |
| mock_tools.return_value.get_available_tools = MagicMock(return_value=[{"name": "nmap", "description": "Port scanner"}]) | |
| agent = AutonomousAgent(llm_client=mock_llm_client) | |
| capabilities = agent.get_capabilities() | |
| assert "version" in capabilities | |
| assert "safety_level" in capabilities | |
| assert "max_iterations" in capabilities | |
| assert "available_tools" in capabilities | |
| assert "features" in capabilities | |
| assert len(capabilities["features"]) > 0 | |
| async def test_agent_exploit_with_proper_safety(mock_llm_client): | |
| """Test exploitation with proper safety level.""" | |
| with ( | |
| patch("autonomous.agent.ReActLoop") as mock_react, | |
| patch("autonomous.agent.MemoryManager") as mock_mem, | |
| patch("autonomous.agent.ToolExecutor") as mock_tools, | |
| ): | |
| mock_react.return_value = MagicMock() | |
| mock_react.return_value.run = AsyncMock( | |
| return_value={ | |
| "goal": "Exploit RCE on example.com", | |
| "completed": True, | |
| "steps_taken": 2, | |
| "history": [], | |
| } | |
| ) | |
| mock_mem.return_value = MagicMock() | |
| mock_mem.return_value.record_episode = AsyncMock() | |
| mock_tools.return_value = MagicMock() | |
| mock_tools.return_value.get_available_tools = MagicMock(return_value=[]) | |
| # Create agent with EXPLOIT level | |
| config = AgentConfig(safety_level=SafetyLevel.EXPLOIT) | |
| agent = AutonomousAgent(llm_client=mock_llm_client, config=config) | |
| result = await agent.exploit_target("example.com", "RCE") | |
| # Should proceed with exploitation | |
| assert "error" not in result | |
| mock_react.return_value.run.assert_called_once() | |
| def test_agent_compile_report(mock_llm_client): | |
| """Test _compile_report method.""" | |
| with ( | |
| patch("autonomous.agent.ToolExecutor"), | |
| patch("autonomous.agent.MemoryManager"), | |
| patch("autonomous.agent.ReActLoop"), | |
| ): | |
| agent = AutonomousAgent(llm_client=mock_llm_client) | |
| react_result = { | |
| "goal": "Test goal", | |
| "completed": True, | |
| "steps_taken": 3, | |
| "history": [ | |
| {"type": "action", "tool": "nmap"}, | |
| { | |
| "type": "observation", | |
| "result": {"findings": [{"type": "open_port", "severity": "info"}]}, | |
| }, | |
| {"type": "action", "tool": "nuclei"}, | |
| ], | |
| } | |
| report = agent._compile_report(react_result, "example.com") | |
| assert report["summary"]["goal"] == "Test goal" | |
| assert report["summary"]["target"] == "example.com" | |
| assert report["summary"]["completed"] is True | |
| assert report["summary"]["steps_taken"] == 3 | |
| assert "nmap" in report["summary"]["tools_used"] | |
| assert "nuclei" in report["summary"]["tools_used"] | |
| assert len(report["findings"]) > 0 | |
| def test_agent_calculate_duration(mock_llm_client): | |
| """Test _calculate_duration method.""" | |
| with ( | |
| patch("autonomous.agent.ToolExecutor"), | |
| patch("autonomous.agent.MemoryManager"), | |
| patch("autonomous.agent.ReActLoop"), | |
| ): | |
| agent = AutonomousAgent(llm_client=mock_llm_client) | |
| # Test with steps | |
| result = {"steps_taken": 10, "history": []} | |
| duration = agent._calculate_duration(result) | |
| assert duration == 50.0 # 10 * 5.0 | |
| # Test with empty history | |
| result = {"history": []} | |
| duration = agent._calculate_duration(result) | |
| assert duration == 0.0 | |
Xet Storage Details
- Size:
- 19 kB
- Xet hash:
- 9a984984165d6828d39d60016c24fdd712243e3a6aff20fa5735bd949445ea2b
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.