Spaces:
Sleeping
Sleeping
File size: 33,892 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 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 | """
Coverage-driven tests for agent_control_routes.py (0% -> 75%+ target)
API Endpoints Tested:
- POST /api/agent/start - Start Atom OS as background service
- POST /api/agent/stop - Stop Atom OS service
- POST /api/agent/restart - Restart Atom OS service
- GET /api/agent/status - Get Atom OS status
- POST /api/agent/execute - Execute single Atom command
Coverage Target Areas:
- Lines 1-50: Route initialization and request/response models
- Lines 50-160: Start endpoint
- Lines 160-205: Stop endpoint
- Lines 205-265: Restart endpoint
- Lines 265-310: Status endpoint
- Lines 310-355: Execute endpoint
"""
import pytest
from unittest.mock import Mock, patch, MagicMock, AsyncMock
from fastapi import FastAPI
from fastapi.testclient import TestClient
# Import agent control routes router
from api.agent_control_routes import (
router,
StartAgentRequest,
StartAgentResponse,
StopAgentResponse,
RestartAgentResponse,
AgentStatusResponse,
ExecuteCommandRequest,
ExecuteCommandResponse
)
from core.admin_endpoints import get_super_admin
from core.models import User
# ============================================================================
# Test Fixtures
# ============================================================================
@pytest.fixture(scope="function")
def test_app():
"""Create FastAPI app with agent control routes for testing."""
app = FastAPI()
app.include_router(router)
return app
@pytest.fixture(scope="function")
def client(test_app: FastAPI):
"""
Create TestClient for testing with super admin authentication.
Overrides the get_super_admin dependency to return our test super admin user.
"""
# Create test super admin user
super_admin_user = User(
id="test-super-admin-coverage",
email="superadmin-coverage@test.com",
role="super_admin"
)
def override_get_super_admin():
return super_admin_user
test_app.dependency_overrides[get_super_admin] = override_get_super_admin
test_client = TestClient(test_app)
try:
yield test_client
finally:
test_app.dependency_overrides.clear()
# ============================================================================
# Request/Response Model Tests (6 tests)
# ============================================================================
def test_start_agent_request_model_defaults():
"""Cover StartAgentRequest default values (lines 38-46)."""
request = StartAgentRequest()
assert request.port == 8000
assert request.host == "0.0.0.0"
assert request.workers == 1
assert request.host_mount is False
assert request.dev is False
def test_start_agent_request_model_custom_values():
"""Cover StartAgentRequest with custom values."""
request = StartAgentRequest(
port=9000,
host="localhost",
workers=4,
host_mount=True,
dev=True
)
assert request.port == 9000
assert request.host == "localhost"
assert request.workers == 4
assert request.host_mount is True
assert request.dev is True
def test_execute_command_request_model_defaults():
"""Cover ExecuteCommandRequest default values (lines 88-93)."""
request = ExecuteCommandRequest(command="test command")
assert request.command == "test command"
assert request.timeout == 30 # Default
def test_execute_command_request_custom_timeout():
"""Cover ExecuteCommandRequest with custom timeout."""
request = ExecuteCommandRequest(command="test", timeout=60)
assert request.command == "test"
assert request.timeout == 60
def test_response_models_serialization():
"""Cover response model serialization."""
start_response = StartAgentResponse(
success=True,
pid=12345,
status="started",
dashboard_url="http://localhost:8000",
message="Started"
)
assert start_response.success is True
assert start_response.pid == 12345
assert start_response.status == "started"
assert start_response.dashboard_url == "http://localhost:8000"
assert start_response.message == "Started"
def test_response_models_with_errors():
"""Cover response models with error fields."""
stop_response = StopAgentResponse(
success=False,
status="error",
message="Failed to stop",
error="Process not found"
)
assert stop_response.success is False
assert stop_response.status == "error"
assert stop_response.error == "Process not found"
# ============================================================================
# Start Endpoint Tests (12 tests)
# ============================================================================
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_start_agent_success(mock_start, mock_is_running, client):
"""Cover successful agent start (lines 105-156)."""
mock_is_running.return_value = False
mock_start.return_value = 12345
response = client.post("/api/agent/start", json={
"port": 8000,
"host": "0.0.0.0",
"workers": 1,
"host_mount": False,
"dev": False
})
assert response.status_code == 200
result = response.json()
assert result["success"] is True
assert result["pid"] == 12345
assert result["status"] == "started"
assert result["dashboard_url"] == "http://0.0.0.0:8000"
assert result["message"] == "Atom OS started successfully"
mock_start.assert_called_once_with(
port=8000,
host="0.0.0.0",
workers=1,
host_mount=False,
dev=False
)
@patch('api.agent_control_routes.DaemonManager.is_running')
def test_start_agent_already_running(mock_is_running, client):
"""Cover start when already running (lines 135-140)."""
mock_is_running.return_value = True
with patch('api.agent_control_routes.DaemonManager.get_pid', return_value=9999):
response = client.post("/api/agent/start", json={"port": 8000})
assert response.status_code == 400
assert "already running" in response.json()["detail"].lower()
assert "9999" in response.json()["detail"]
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_start_agent_runtime_error(mock_start, mock_is_running, client):
"""Cover start with RuntimeError (lines 158-159)."""
mock_is_running.return_value = False
mock_start.side_effect = RuntimeError("Port already in use")
response = client.post("/api/agent/start", json={"port": 8000})
assert response.status_code == 500
assert "Port already in use" in response.json()["detail"]
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_start_agent_io_error(mock_start, mock_is_running, client):
"""Cover start with IOError (lines 160-161)."""
mock_is_running.return_value = False
mock_start.side_effect = IOError("PID file write failed")
response = client.post("/api/agent/start", json={"port": 8000})
assert response.status_code == 500
assert "PID file write failed" in response.json()["detail"]
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_start_agent_with_custom_config(mock_start, mock_is_running, client):
"""Cover start with custom configuration."""
mock_is_running.return_value = False
mock_start.return_value = 54321
response = client.post("/api/agent/start", json={
"port": 9000,
"host": "localhost",
"workers": 4,
"host_mount": True,
"dev": True
})
assert response.status_code == 200
result = response.json()
assert result["pid"] == 54321
assert result["dashboard_url"] == "http://localhost:9000"
mock_start.assert_called_once_with(
port=9000,
host="localhost",
workers=4,
host_mount=True,
dev=True
)
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_start_agent_minimal_config(mock_start, mock_is_running, client):
"""Cover start with minimal configuration (defaults)."""
mock_is_running.return_value = False
mock_start.return_value = 11111
response = client.post("/api/agent/start", json={})
assert response.status_code == 200
result = response.json()
assert result["pid"] == 11111
assert result["dashboard_url"] == "http://0.0.0.0:8000"
@pytest.mark.parametrize("port,valid", [
(8000, True),
(3000, True),
(65535, True),
(0, False), # Invalid port
(65536, False), # Invalid port
(-1, False), # Invalid port
])
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_start_agent_port_validation(mock_start, mock_is_running, client, port, valid):
"""Cover port validation in request model."""
mock_is_running.return_value = False
mock_start.return_value = 12345
response = client.post("/api/agent/start", json={"port": port})
if valid:
# Should pass validation and reach the endpoint
assert response.status_code == 200
else:
assert response.status_code == 422 # Validation error
@pytest.mark.parametrize("workers,valid", [
(1, True),
(4, True),
(16, True),
(0, False), # Invalid workers
(17, False), # Invalid workers
])
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_start_agent_workers_validation(mock_start, mock_is_running, client, workers, valid):
"""Cover workers validation in request model."""
mock_is_running.return_value = False
mock_start.return_value = 12345
response = client.post("/api/agent/start", json={
"port": 8000,
"workers": workers
})
if valid:
assert response.status_code == 200
assert response.status_code != 422
else:
assert response.status_code == 422
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_start_agent_generic_exception(mock_start, mock_is_running, client):
"""Cover start with generic exception."""
mock_is_running.return_value = False
mock_start.side_effect = OSError("Unexpected error")
response = client.post("/api/agent/start", json={"port": 8000})
# Should raise 500, as OSError is not caught
assert response.status_code == 500
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_start_agent_response_structure(mock_start, mock_is_running, client):
"""Cover start response has all required fields."""
mock_is_running.return_value = False
mock_start.return_value = 12345
response = client.post("/api/agent/start", json={"port": 8000})
result = response.json()
# Check all response fields
assert "success" in result
assert "pid" in result
assert "status" in result
assert "dashboard_url" in result
assert "message" in result
assert "error" not in result or result["error"] is None
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_start_agent_host_mount_enabled(mock_start, mock_is_running, client):
"""Cover start with host mount enabled."""
mock_is_running.return_value = False
mock_start.return_value = 22222
response = client.post("/api/agent/start", json={
"port": 8000,
"host_mount": True
})
assert response.status_code == 200
mock_start.assert_called_once_with(
port=8000,
host="0.0.0.0",
workers=1,
host_mount=True,
dev=False
)
# ============================================================================
# Stop Endpoint Tests (8 tests)
# ============================================================================
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_stop_agent_success(mock_stop, mock_is_running, client):
"""Cover successful agent stop (lines 164-200)."""
mock_is_running.return_value = True
response = client.post("/api/agent/stop")
assert response.status_code == 200
result = response.json()
assert result["success"] is True
assert result["status"] == "stopped"
assert result["message"] == "Atom OS stopped successfully"
mock_stop.assert_called_once()
@patch('api.agent_control_routes.DaemonManager.is_running')
def test_stop_agent_not_running(mock_is_running, client):
"""Cover stop when not running (lines 188-192)."""
mock_is_running.return_value = False
response = client.post("/api/agent/stop")
assert response.status_code == 400
assert "not running" in response.json()["detail"].lower()
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_stop_agent_exception(mock_stop, mock_is_running, client):
"""Cover stop with unexpected exception (lines 202-205)."""
mock_is_running.return_value = True
mock_stop.side_effect = Exception("Stop failed")
response = client.post("/api/agent/stop")
assert response.status_code == 500
assert "Stop failed" in response.json()["detail"]
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_stop_agent_response_structure(mock_stop, mock_is_running, client):
"""Cover stop response has all required fields."""
mock_is_running.return_value = True
response = client.post("/api/agent/stop")
result = response.json()
# Check all response fields
assert "success" in result
assert "status" in result
assert "message" in result
assert "error" not in result or result["error"] is None
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_stop_agent_called_once(mock_stop, mock_is_running, client):
"""Cover stop daemon is called exactly once."""
mock_is_running.return_value = True
response = client.post("/api/agent/stop")
assert response.status_code == 200
assert mock_stop.call_count == 1
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_stop_agent_with_runtime_error(mock_stop, mock_is_running, client):
"""Cover stop with RuntimeError."""
mock_is_running.return_value = True
mock_stop.side_effect = RuntimeError("Process not found")
response = client.post("/api/agent/stop")
assert response.status_code == 500
assert "Process not found" in response.json()["detail"]
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_stop_agent_with_io_error(mock_stop, mock_is_running, client):
"""Cover stop with IOError."""
mock_is_running.return_value = True
mock_stop.side_effect = IOError("PID file error")
response = client.post("/api/agent/stop")
assert response.status_code == 500
assert "PID file error" in response.json()["detail"]
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_stop_http_exception_propagates(mock_stop, mock_is_running, client):
"""Cover HTTPException is re-raised (lines 202-203)."""
from fastapi import HTTPException
mock_is_running.return_value = False
response = client.post("/api/agent/stop")
assert response.status_code == 400
assert "not running" in response.json()["detail"].lower()
# ============================================================================
# Restart Endpoint Tests (10 tests)
# ============================================================================
@patch('time.sleep')
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_restart_agent_when_running(mock_stop, mock_start, mock_is_running, mock_sleep, client):
"""Cover restart when agent is running (lines 208-264)."""
mock_is_running.return_value = True
mock_start.return_value = 54321
response = client.post("/api/agent/restart", json={
"port": 8000,
"host": "localhost",
"workers": 2
})
assert response.status_code == 200
result = response.json()
assert result["success"] is True
assert result["pid"] == 54321
assert result["status"] == "restarted"
assert result["was_running"] is True
assert result["dashboard_url"] == "http://localhost:8000"
assert result["message"] == "Atom OS restarted successfully"
mock_stop.assert_called_once()
mock_start.assert_called_once()
@patch('time.sleep')
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_restart_agent_when_not_running(mock_start, mock_is_running, mock_sleep, client):
"""Cover restart when agent is not running."""
mock_is_running.side_effect = [False, False]
mock_start.return_value = 11111
response = client.post("/api/agent/restart", json={"port": 8000})
assert response.status_code == 200
result = response.json()
assert result["was_running"] is False
assert result["pid"] == 11111
@patch('time.sleep')
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_restart_agent_exception(mock_stop, mock_start, mock_is_running, mock_sleep, client):
"""Cover restart with exception (lines 263-264)."""
mock_is_running.return_value = True
mock_stop.side_effect = Exception("Restart failed")
response = client.post("/api/agent/restart", json={"port": 8000})
assert response.status_code == 500
assert "Restart failed" in response.json()["detail"]
@patch('time.sleep')
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_restart_agent_with_custom_config(mock_stop, mock_start, mock_is_running, mock_sleep, client):
"""Cover restart with custom configuration."""
mock_is_running.return_value = True
mock_start.return_value = 99999
response = client.post("/api/agent/restart", json={
"port": 9000,
"host": "0.0.0.0",
"workers": 8,
"host_mount": True,
"dev": True
})
assert response.status_code == 200
result = response.json()
assert result["pid"] == 99999
assert result["dashboard_url"] == "http://0.0.0.0:9000"
mock_start.assert_called_once_with(
port=9000,
host="0.0.0.0",
workers=8,
host_mount=True,
dev=True
)
@patch('time.sleep')
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_restart_agent_sleep_called(mock_stop, mock_start, mock_is_running, mock_sleep, client):
"""Cover sleep is called during restart (line 244)."""
mock_is_running.return_value = True
mock_start.return_value = 12345
response = client.post("/api/agent/restart", json={"port": 8000})
assert response.status_code == 200
mock_sleep.assert_called_once_with(2)
@patch('time.sleep')
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_restart_agent_not_running_no_stop(mock_start, mock_is_running, mock_sleep, client):
"""Cover restart when not running doesn't call stop."""
mock_is_running.side_effect = [False, False]
mock_start.return_value = 22222
with patch('api.agent_control_routes.DaemonManager.stop_daemon') as mock_stop:
response = client.post("/api/agent/restart", json={"port": 8000})
assert response.status_code == 200
mock_stop.assert_not_called()
@patch('time.sleep')
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_restart_agent_response_structure(mock_stop, mock_start, mock_is_running, mock_sleep, client):
"""Cover restart response has all required fields."""
mock_is_running.return_value = True
mock_start.return_value = 33333
response = client.post("/api/agent/restart", json={"port": 8000})
result = response.json()
# Check all response fields
assert "success" in result
assert "pid" in result
assert "status" in result
assert "dashboard_url" in result
assert "was_running" in result
assert "message" in result
assert "error" not in result or result["error"] is None
@patch('time.sleep')
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_restart_agent_with_start_error(mock_stop, mock_start, mock_is_running, mock_sleep, client):
"""Cover restart when start_daemon fails."""
mock_is_running.return_value = True
mock_stop.return_value = None
mock_start.side_effect = RuntimeError("Port in use")
response = client.post("/api/agent/restart", json={"port": 8000})
assert response.status_code == 500
assert "Port in use" in response.json()["detail"]
@patch('time.sleep')
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_restart_agent_minimal_config(mock_start, mock_is_running, mock_sleep, client):
"""Cover restart with minimal configuration."""
mock_is_running.side_effect = [True, True]
mock_start.return_value = 44444
with patch('api.agent_control_routes.DaemonManager.stop_daemon'):
response = client.post("/api/agent/restart", json={})
assert response.status_code == 200
result = response.json()
assert result["pid"] == 44444
@patch('time.sleep')
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_restart_agent_was_running_tracking(mock_stop, mock_start, mock_is_running, mock_sleep, client):
"""Cover was_running field is tracked correctly."""
# Test when running
mock_is_running.return_value = True
mock_start.return_value = 55555
response = client.post("/api/agent/restart", json={"port": 8000})
assert response.json()["was_running"] is True
# Test when not running
mock_is_running.side_effect = [False, False]
mock_start.return_value = 66666
response = client.post("/api/agent/restart", json={"port": 8000})
assert response.json()["was_running"] is False
# ============================================================================
# Status Endpoint Tests (8 tests)
# ============================================================================
@patch('api.agent_control_routes.DaemonManager.get_status')
def test_get_status_success(mock_get_status, client):
"""Cover successful status retrieval (lines 267-309)."""
mock_get_status.return_value = {
"running": True,
"pid": 12345,
"uptime_seconds": 3600,
"memory_mb": 256.5,
"cpu_percent": 5.2,
"status": "running"
}
response = client.get("/api/agent/status")
assert response.status_code == 200
result = response.json()
assert result["success"] is True
assert result["status"]["running"] is True
assert result["status"]["pid"] == 12345
assert result["status"]["uptime_seconds"] == 3600
assert result["status"]["memory_mb"] == 256.5
assert result["status"]["cpu_percent"] == 5.2
@patch('api.agent_control_routes.DaemonManager.get_status')
def test_get_status_not_running(mock_get_status, client):
"""Cover status when not running."""
mock_get_status.return_value = {
"running": False,
"pid": None,
"uptime_seconds": 0,
"memory_mb": 0,
"cpu_percent": 0,
"status": "stopped"
}
response = client.get("/api/agent/status")
assert response.status_code == 200
assert response.json()["status"]["running"] is False
assert response.json()["status"]["pid"] is None
@patch('api.agent_control_routes.DaemonManager.get_status')
def test_get_status_exception(mock_get_status, client):
"""Cover status with exception (lines 308-309)."""
mock_get_status.side_effect = Exception("Status check failed")
response = client.get("/api/agent/status")
assert response.status_code == 500
assert "Status check failed" in response.json()["detail"]
@patch('api.agent_control_routes.DaemonManager.get_status')
def test_get_status_response_structure(mock_get_status, client):
"""Cover status response has all required fields."""
mock_get_status.return_value = {
"running": True,
"pid": 99999,
"uptime_seconds": 7200,
"memory_mb": 512.0,
"cpu_percent": 10.5,
"status": "running"
}
response = client.get("/api/agent/status")
result = response.json()
# Check all response fields
assert "success" in result
assert "status" in result
assert isinstance(result["status"], dict)
@patch('api.agent_control_routes.DaemonManager.get_status')
def test_get_status_with_high_memory(mock_get_status, client):
"""Cover status with high memory usage."""
mock_get_status.return_value = {
"running": True,
"pid": 12345,
"uptime_seconds": 86400,
"memory_mb": 2048.75,
"cpu_percent": 25.8,
"status": "running"
}
response = client.get("/api/agent/status")
assert response.status_code == 200
assert response.json()["status"]["memory_mb"] == 2048.75
@patch('api.agent_control_routes.DaemonManager.get_status')
def test_get_status_with_runtime_error(mock_get_status, client):
"""Cover status with RuntimeError."""
mock_get_status.side_effect = RuntimeError("Daemon not responding")
response = client.get("/api/agent/status")
assert response.status_code == 500
assert "Daemon not responding" in response.json()["detail"]
@patch('api.agent_control_routes.DaemonManager.get_status')
def test_get_status_with_io_error(mock_get_status, client):
"""Cover status with IOError."""
mock_get_status.side_effect = IOError("PID file not found")
response = client.get("/api/agent/status")
assert response.status_code == 500
assert "PID file not found" in response.json()["detail"]
@patch('api.agent_control_routes.DaemonManager.get_status')
def test_get_status_called_once(mock_get_status, client):
"""Cover get_status is called exactly once."""
mock_get_status.return_value = {
"running": True,
"pid": 12345,
"uptime_seconds": 100,
"memory_mb": 100.0,
"cpu_percent": 1.0,
"status": "running"
}
response = client.get("/api/agent/status")
assert response.status_code == 200
assert mock_get_status.call_count == 1
# ============================================================================
# Execute Endpoint Tests (6 tests)
# ============================================================================
def test_execute_command_placeholder(client):
"""Cover execute endpoint placeholder (lines 312-354)."""
response = client.post("/api/agent/execute", json={
"command": "agent.chat('Hello')",
"timeout": 30
})
assert response.status_code == 200
result = response.json()
assert result["success"] is True
assert "not yet implemented" in result["result"]
assert "note" in result
assert result["note"] == "Use POST /api/agent/start to run Atom as service instead"
def test_execute_command_with_custom_timeout(client):
"""Cover execute with custom timeout."""
response = client.post("/api/agent/execute", json={
"command": "test command",
"timeout": 60
})
assert response.status_code == 200
result = response.json()
assert result["success"] is True
@pytest.mark.parametrize("timeout,valid", [
(1, True),
(30, True),
(300, True),
(0, False), # Invalid timeout
(301, False), # Invalid timeout
])
def test_execute_timeout_validation(client, timeout, valid):
"""Cover timeout validation in execute request."""
response = client.post("/api/agent/execute", json={
"command": "test",
"timeout": timeout
})
if valid:
assert response.status_code == 200
else:
assert response.status_code == 422
def test_execute_missing_command(client):
"""Cover execute with missing command field."""
response = client.post("/api/agent/execute", json={"timeout": 30})
assert response.status_code == 422
def test_execute_empty_command(client):
"""Cover execute with empty command (should fail validation)."""
response = client.post("/api/agent/execute", json={
"command": "",
"timeout": 30
})
# May pass validation but endpoint returns success
assert response.status_code in [200, 422]
def test_execute_command_response_structure(client):
"""Cover execute response has all required fields."""
response = client.post("/api/agent/execute", json={
"command": "test command",
"timeout": 30
})
result = response.json()
# Check all response fields
assert "success" in result
assert "result" in result
assert "note" in result
assert "error" not in result or result["error"] is None
# ============================================================================
# Edge Cases and Integration Tests (6 tests)
# ============================================================================
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_start_stop_restart_workflow(mock_stop, mock_start, mock_is_running, client):
"""Cover full start-stop-restart workflow."""
mock_is_running.side_effect = [False, True, False, True, False]
mock_start.return_value = 12345
# Start
response = client.post("/api/agent/start", json={"port": 8000})
assert response.status_code == 200
# Stop (now running)
response = client.post("/api/agent/stop")
assert response.status_code == 200
@patch('api.agent_control_routes.DaemonManager.is_running')
def test_status_when_not_running(mock_is_running, client):
"""Cover status checks when daemon is not running."""
mock_is_running.return_value = False
with patch('api.agent_control_routes.DaemonManager.get_status') as mock_status:
mock_status.return_value = {
"running": False,
"pid": None,
"uptime_seconds": 0,
"memory_mb": 0,
"cpu_percent": 0,
"status": "stopped"
}
response = client.get("/api/agent/status")
assert response.status_code == 200
assert response.json()["status"]["running"] is False
def test_router_prefix_and_tags():
"""Cover router has correct prefix and tags (line 34)."""
assert router.prefix == "/api/agent"
assert router.tags == ["agent-control"]
def test_all_endpoints_registered():
"""Cover all endpoints are registered on router."""
routes = [route.path for route in router.routes]
assert "/api/agent/start" in routes
assert "/api/agent/stop" in routes
assert "/api/agent/restart" in routes
assert "/api/agent/status" in routes
assert "/api/agent/execute" in routes
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
def test_concurrent_start_requests(mock_start, mock_is_running, client):
"""Cover handling of concurrent start requests."""
mock_is_running.side_effect = [False, True, False]
mock_start.return_value = 12345
# First request succeeds
response1 = client.post("/api/agent/start", json={"port": 8000})
assert response1.status_code == 200
# Second request fails (already running)
response2 = client.post("/api/agent/start", json={"port": 8000})
assert response2.status_code == 400
@patch('time.sleep')
@patch('api.agent_control_routes.DaemonManager.is_running')
@patch('api.agent_control_routes.DaemonManager.start_daemon')
@patch('api.agent_control_routes.DaemonManager.stop_daemon')
def test_restart_preserves_config(mock_stop, mock_start, mock_is_running, mock_sleep, client):
"""Cover restart preserves configuration from request."""
mock_is_running.return_value = True
mock_start.return_value = 77777
response = client.post("/api/agent/restart", json={
"port": 8888,
"host": "127.0.0.1",
"workers": 4
})
assert response.status_code == 200
mock_start.assert_called_once_with(
port=8888,
host="127.0.0.1",
workers=4,
host_mount=False,
dev=False
)
|