File size: 16,882 Bytes
cc036ff | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 | """
Agent Routes API Tests
Comprehensive tests for agent management endpoints from api/agent_routes.py.
Tests cover agent CRUD, lifecycle, status tracking, permissions, and meta-agent operations.
"""
import pytest
from datetime import datetime
from unittest.mock import AsyncMock, Mock, patch, MagicMock
from fastapi.testclient import TestClient
from fastapi import FastAPI, BackgroundTasks
from sqlalchemy.orm import Session
from api.agent_routes import router
from core.models import AgentRegistry, AgentJob, AgentFeedback, HITLAction, HITLActionStatus, User
# ============================================================================
# Fixtures
# ============================================================================
_current_test_user = None
@pytest.fixture
def client(db: Session):
"""Create TestClient for agent routes with database override."""
global _current_test_user
_current_test_user = None
app = FastAPI()
app.include_router(router)
from core.database import get_db
from core.security_dependencies import get_current_user
from core.rbac_service import Permission
def override_get_db():
yield db
def override_get_current_user():
return _current_test_user
app.dependency_overrides[get_db] = override_get_db
app.dependency_overrides[get_current_user] = override_get_current_user
test_client = TestClient(app, raise_server_exceptions=False)
yield test_client
app.dependency_overrides.clear()
_current_test_user = None
@pytest.fixture
def mock_admin_user(db: Session):
"""Create admin user with all permissions."""
import uuid
user_id = str(uuid.uuid4())
user = User(
id=user_id,
email=f"admin-{user_id}@example.com",
first_name="Admin",
last_name="User",
role="admin",
status="active"
)
db.add(user)
db.commit()
db.refresh(user)
return user
@pytest.fixture
def mock_member_user(db: Session):
"""Create regular member user."""
import uuid
user_id = str(uuid.uuid4())
user = User(
id=user_id,
email=f"member-{user_id}@example.com",
first_name="Member",
last_name="User",
role="member",
status="active"
)
db.add(user)
db.commit()
db.refresh(user)
return user
@pytest.fixture
def mock_agent(db: Session):
"""Create test agent."""
import uuid
agent_id = str(uuid.uuid4())
agent = AgentRegistry(
id=agent_id,
name=f"Test Agent {agent_id[:8]}",
description="Test agent for testing",
category="testing",
status="idle",
confidence_score=0.75,
module_path="test.module",
class_name="TestClass"
)
db.add(agent)
db.commit()
db.refresh(agent)
return agent
@pytest.fixture
def mock_agent_job(db: Session, mock_agent: AgentRegistry):
"""Create test agent job."""
import uuid
job = AgentJob(
id=str(uuid.uuid4()),
agent_id=mock_agent.id,
status="completed",
start_time=datetime.utcnow(),
end_time=datetime.utcnow()
)
db.add(job)
db.commit()
db.refresh(job)
return job
# ============================================================================
# GET / - List Agents Tests
# ============================================================================
def test_list_agents_success(
client: TestClient,
db: Session,
mock_agent: AgentRegistry,
mock_admin_user: User
):
"""Test list agents successfully."""
global _current_test_user
_current_test_user = mock_admin_user
response = client.get("/api/agents/")
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
assert len(data) >= 1
def test_list_agents_with_category_filter(
client: TestClient,
db: Session,
mock_agent: AgentRegistry,
mock_admin_user: User
):
"""Test list agents with category filter."""
global _current_test_user
_current_test_user = mock_admin_user
response = client.get(f"/api/agents/?category={mock_agent.category}")
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
# ============================================================================
# POST /{agent_id}/run - Run Agent Tests
# ============================================================================
def test_run_agent_success(
client: TestClient,
db: Session,
mock_agent: AgentRegistry,
mock_member_user: User
):
"""Test run agent successfully."""
global _current_test_user
_current_test_user = mock_member_user
request_data = {
"parameters": {
"test_param": "test_value"
}
}
response = client.post(f"/api/agents/{mock_agent.id}/run", json=request_data)
# Should return success (background task started)
assert response.status_code in [200, 202]
def test_run_agent_sync_mode(
client: TestClient,
db: Session,
mock_agent: AgentRegistry,
mock_member_user: User
):
"""Test run agent in synchronous mode."""
global _current_test_user
_current_test_user = mock_member_user
request_data = {
"parameters": {
"sync": True,
"test_input": "test"
}
}
with patch('api.agent_routes.execute_agent_task') as mock_exec:
mock_exec.return_value = {"result": "test output"}
response = client.post(f"/api/agents/{mock_agent.id}/run", json=request_data)
# Should execute synchronously
assert response.status_code in [200, 202]
def test_run_agent_not_found(
client: TestClient,
db: Session,
mock_member_user: User
):
"""Test run non-existent agent."""
global _current_test_user
_current_test_user = mock_member_user
request_data = {
"parameters": {}
}
response = client.post("/api/agents/nonexistent-agent/run", json=request_data)
assert response.status_code == 404
# ============================================================================
# POST /{agent_id}/feedback - Submit Feedback Tests
# ============================================================================
def test_submit_agent_feedback(
client: TestClient,
db: Session,
mock_agent: AgentRegistry,
mock_member_user: User
):
"""Test submit agent feedback successfully."""
global _current_test_user
_current_test_user = mock_member_user
feedback_data = {
"original_output": "Agent output",
"user_correction": "Corrected output",
"input_context": "Task context"
}
with patch('core.agent_governance_service.AgentGovernanceService.submit_feedback') as mock_feedback:
mock_feedback.return_value = Mock(
id="feedback-123",
status="pending",
ai_reasoning="Processing feedback"
)
response = client.post(f"/api/agents/{mock_agent.id}/feedback", json=feedback_data)
assert response.status_code == 200
data = response.json()
assert "feedback_id" in data or "success" in data
# ============================================================================
# POST /{agent_id}/promote - Promote Agent Tests
# ============================================================================
def test_promote_agent_to_autonomous(
client: TestClient,
db: Session,
mock_agent: AgentRegistry,
mock_admin_user: User
):
"""Test promote agent to autonomous successfully."""
global _current_test_user
_current_test_user = mock_admin_user
with patch('core.agent_governance_service.AgentGovernanceService.promote_to_autonomous') as mock_promote:
mock_promote.return_value = mock_agent
response = client.post(f"/api/agents/{mock_agent.id}/promote")
assert response.status_code == 200
data = response.json()
assert "agent_status" in data or "success" in data
# ============================================================================
# GET /approvals/pending - List Pending Approvals Tests
# ============================================================================
def test_list_pending_approvals(
client: TestClient,
db: Session,
mock_admin_user: User
):
"""Test list pending approvals successfully."""
global _current_test_user
_current_test_user = mock_admin_user
response = client.get("/api/agents/approvals/pending")
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
# ============================================================================
# POST /approvals/{action_id} - Decide HITL Action Tests
# ============================================================================
def test_approve_hitl_action(
client: TestClient,
db: Session,
mock_admin_user: User
):
"""Test approve HITL action successfully."""
global _current_test_user
_current_test_user = mock_admin_user
import uuid
action_id = str(uuid.uuid4())
approval_data = {
"decision": "approved",
"feedback": "Looks good"
}
# Create mock HITL action
mock_action = Mock()
mock_action.id = action_id
mock_action.status = HITLActionStatus.PENDING.value
with patch('core.models.HITLAction') as mock_hitl:
mock_hitl.query.return_value.filter.return_value.first.return_value = mock_action
with patch('core.websockets.manager.broadcast') as mock_ws:
response = client.post(f"/api/agents/approvals/{action_id}", json=approval_data)
assert response.status_code == 200
def test_reject_hitl_action(
client: TestClient,
db: Session,
mock_admin_user: User
):
"""Test reject HITL action successfully."""
global _current_test_user
_current_test_user = mock_admin_user
import uuid
action_id = str(uuid.uuid4())
approval_data = {
"decision": "rejected",
"feedback": "Needs correction"
}
mock_action = Mock()
mock_action.id = action_id
mock_action.status = HITLActionStatus.PENDING.value
with patch('core.models.HITLAction') as mock_hitl:
mock_hitl.query.return_value.filter.return_value.first.return_value = mock_action
with patch('core.websockets.manager.broadcast') as mock_ws:
response = client.post(f"/api/agents/approvals/{action_id}", json=approval_data)
assert response.status_code == 200
# ============================================================================
# POST /atom/execute - Execute Meta-Agent Tests
# ============================================================================
def test_execute_atom_meta_agent(
client: TestClient,
db: Session,
mock_member_user: User
):
"""Test execute Atom meta-agent successfully."""
global _current_test_user
_current_test_user = mock_member_user
request_data = {
"request": "Analyze sales data",
"context": {}
}
with patch('core.atom_meta_agent.handle_manual_trigger') as mock_trigger:
mock_trigger.return_value = {
"result": "Analysis complete"
}
response = client.post("/api/agents/atom/execute", json=request_data)
assert response.status_code == 200
# ============================================================================
# POST /spawn - Spawn Agent Tests
# ============================================================================
def test_spawn_custom_agent(
client: TestClient,
db: Session,
mock_admin_user: User
):
"""Test spawn custom agent successfully."""
global _current_test_user
_current_test_user = mock_admin_user
request_data = {
"template": "finance_analyst",
"custom_params": {},
"persist": False
}
mock_agent = Mock()
mock_agent.id = "spawned-agent-123"
mock_agent.name = "Spawned Agent"
mock_agent.category = "finance"
with patch('core.atom_meta_agent.get_atom_agent') as mock_atom:
mock_atom_instance = Mock()
mock_atom_instance.spawn_agent.return_value = mock_agent
mock_atom.return_value = mock_atom_instance
response = client.post("/api/agents/spawn", json=request_data)
assert response.status_code == 200
data = response.json()
assert "agent_id" in data or "success" in data
# ============================================================================
# POST /atom/trigger - Trigger with Data Tests
# ============================================================================
def test_trigger_atom_with_data(
client: TestClient,
db: Session,
mock_member_user: User
):
"""Test trigger Atom with data event."""
global _current_test_user
_current_test_user = mock_member_user
request_data = {
"event_type": "webhook",
"data": {"key": "value"}
}
with patch('core.atom_meta_agent.handle_data_event_trigger') as mock_trigger:
mock_trigger.return_value = {
"result": "Event processed"
}
response = client.post("/api/agents/atom/trigger", json=request_data)
assert response.status_code == 200
# ============================================================================
# POST /custom - Create Custom Agent Tests
# ============================================================================
def test_create_custom_agent(
client: TestClient,
db: Session,
mock_admin_user: User
):
"""Test create custom agent successfully."""
global _current_test_user
_current_test_user = mock_admin_user
request_data = {
"name": "Custom Test Agent",
"description": "A custom test agent",
"category": "custom",
"configuration": {
"model": "gpt-4",
"temperature": 0.7
},
"schedule_config": None
}
response = client.post("/api/agents/custom", json=request_data)
assert response.status_code == 200
data = response.json()
assert "agent_id" in data or "success" in data
# ============================================================================
# PUT /{agent_id} - Update Agent Tests
# ============================================================================
def test_update_agent(
client: TestClient,
db: Session,
mock_agent: AgentRegistry,
mock_admin_user: User
):
"""Test update agent successfully."""
global _current_test_user
_current_test_user = mock_admin_user
request_data = {
"name": "Updated Agent Name",
"description": "Updated description",
"category": "testing",
"configuration": {
"model": "gpt-4"
},
"schedule_config": None
}
response = client.put(f"/api/agents/{mock_agent.id}", json=request_data)
assert response.status_code == 200
data = response.json()
assert "agent_id" in data or "success" in data
def test_update_agent_not_found(
client: TestClient,
db: Session,
mock_admin_user: User
):
"""Test update non-existent agent."""
global _current_test_user
_current_test_user = mock_admin_user
request_data = {
"name": "Updated Name",
"description": "Updated",
"category": "testing",
"configuration": {},
"schedule_config": None
}
response = client.put("/api/agents/nonexistent-agent", json=request_data)
assert response.status_code == 404
# ============================================================================
# POST /{agent_id}/stop - Stop Agent Tests
# ============================================================================
def test_stop_running_agent(
client: TestClient,
db: Session,
mock_agent: AgentRegistry,
mock_member_user: User
):
"""Test stop running agent successfully."""
global _current_test_user
_current_test_user = mock_member_user
with patch('core.agent_task_registry.agent_task_registry') as mock_registry:
mock_registry.cancel_agent_agent_tasks.return_value = 2
response = client.post(f"/api/agents/{mock_agent.id}/stop")
assert response.status_code == 200
data = response.json()
assert "cancelled_tasks" in data or "success" in data
def test_stop_agent_no_tasks(
client: TestClient,
db: Session,
mock_agent: AgentRegistry,
mock_member_user: User
):
"""Test stop agent with no running tasks."""
global _current_test_user
_current_test_user = mock_member_user
with patch('core.agent_task_registry.agent_task_registry') as mock_registry:
mock_registry.cancel_agent_agent_tasks.return_value = 0
response = client.post(f"/api/agents/{mock_agent.id}/stop")
assert response.status_code == 200
|