Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /unit /test_web_ui.py
"""
Web UI Backend Unit Tests
=========================
100+ Tests für das Web UI Backend:
- API Endpoints für Web UI
- Dashboard Daten
- Report Generation
- WebSocket Handlers
Run: pytest tests/unit/test_web_ui.py -v --tb=short
"""
import json
import os
import sys
import uuid
from datetime import datetime
from unittest.mock import AsyncMock, MagicMock, Mock, PropertyMock, patch
import pytest
from fastapi import WebSocketDisconnect
from starlette.testclient import TestClient
from starlette.websockets import WebSocket
# Setup environment BEFORE any imports
os.environ["ADMIN_PASSWORD"] = "test_password"
os.environ["ADMIN_USERNAME"] = "admin"
os.environ["JWT_SECRET_KEY"] = "test-secret-key-for-testing-only"
os.environ["DATABASE_URL"] = "sqlite:///:memory:"
os.environ["REDIS_URL"] = "redis://localhost:6379/0"
os.environ["CORS_ORIGINS"] = "http://localhost:3000"
os.environ["TESTING"] = "true"
# Add project to path
project_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
sys.path.insert(0, str(project_root))
# ============================================================================
# FIXTURES
# ============================================================================
@pytest.fixture
def mock_scan_request():
"""Mock scan request data"""
return {
"target": "example.com",
"goal": "Test security assessment",
"scan_type": "comprehensive",
"safety_level": "non_destructive",
"scope": {"ports": [80, 443]},
}
@pytest.fixture
def mock_scan_request_minimal():
"""Minimal scan request with defaults"""
return {"target": "test.com"}
@pytest.fixture
def mock_finding():
"""Mock finding data"""
return {
"id": "finding-001",
"type": "vulnerability",
"severity": "HIGH",
"title": "SQL Injection",
"description": "SQL injection vulnerability found",
"target": "example.com",
"evidence": {"payload": "' OR 1=1--"},
"risk_score": {"score": 8.5, "severity": "HIGH"},
"timestamp": datetime.now().isoformat(),
}
@pytest.fixture
def mock_finding_critical():
"""Mock critical finding"""
return {
"id": "finding-002",
"type": "vulnerability",
"severity": "CRITICAL",
"title": "Remote Code Execution",
"description": "RCE vulnerability found",
"target": "example.com",
"tool": "nuclei",
"evidence": {"payload": ";whoami"},
"risk_score": {"score": 9.8, "severity": "CRITICAL"},
"timestamp": datetime.now().isoformat(),
}
@pytest.fixture
def mock_finding_medium():
"""Mock medium finding"""
return {
"id": "finding-003",
"type": "info",
"severity": "MEDIUM",
"title": "Information Disclosure",
"description": "Information leakage",
"target": "example.com",
"tool": "nmap",
"timestamp": datetime.now().isoformat(),
}
@pytest.fixture
def mock_websocket():
"""Mock WebSocket connection"""
websocket = MagicMock(spec=WebSocket)
websocket.accept = AsyncMock()
websocket.send_json = AsyncMock()
websocket.receive_text = AsyncMock(return_value=json.dumps({"type": "ping"}))
websocket.close = AsyncMock()
return websocket
@pytest.fixture
def mock_websocket_with_disconnect():
"""Mock WebSocket that disconnects"""
websocket = MagicMock(spec=WebSocket)
websocket.accept = AsyncMock()
websocket.send_json = AsyncMock()
websocket.receive_text = AsyncMock(side_effect=WebSocketDisconnect())
websocket.close = AsyncMock()
return websocket
@pytest.fixture
def mock_websocket_send_error():
"""Mock WebSocket with send error"""
websocket = MagicMock(spec=WebSocket)
websocket.accept = AsyncMock()
websocket.send_json = AsyncMock(side_effect=Exception("Connection failed"))
websocket.receive_text = AsyncMock(return_value=json.dumps({"type": "ping"}))
return websocket
# ============================================================================
# PYDANTIC MODELS TESTS
# ============================================================================
class TestPydanticModels:
"""Tests für Pydantic Models"""
def test_import_models(self):
"""Test that web_ui models can be imported"""
try:
from web_ui.backend.main import (
DashboardStats,
Finding,
ScanRequest,
ScanStatus,
)
assert ScanRequest is not None
assert ScanStatus is not None
assert Finding is not None
assert DashboardStats is not None
except ImportError as e:
pytest.skip(f"Models not available: {e}")
def test_scan_request_defaults(self):
"""Test ScanRequest default values"""
try:
from web_ui.backend.main import ScanRequest
request = ScanRequest(target="example.com")
assert request.target == "example.com"
assert request.scan_type == "comprehensive"
assert request.safety_level == "non_destructive"
assert request.goal is None
assert request.scope is None
except ImportError:
pytest.skip("ScanRequest not available")
def test_scan_request_full(self):
"""Test ScanRequest with all fields"""
try:
from web_ui.backend.main import ScanRequest
request = ScanRequest(
target="example.com",
goal="Security test",
scan_type="quick",
safety_level="read_only",
scope={"ports": [80, 443]},
)
assert request.target == "example.com"
assert request.goal == "Security test"
assert request.scan_type == "quick"
assert request.safety_level == "read_only"
assert request.scope == {"ports": [80, 443]}
except ImportError:
pytest.skip("ScanRequest not available")
def test_scan_request_types(self):
"""Test different scan types"""
try:
from web_ui.backend.main import ScanRequest
types = ["quick", "standard", "comprehensive"]
for scan_type in types:
request = ScanRequest(target="test.com", scan_type=scan_type)
assert request.scan_type == scan_type
except ImportError:
pytest.skip("ScanRequest not available")
def test_scan_request_safety_levels(self):
"""Test different safety levels"""
try:
from web_ui.backend.main import ScanRequest
levels = ["read_only", "non_destructive", "destructive", "exploit"]
for level in levels:
request = ScanRequest(target="test.com", safety_level=level)
assert request.safety_level == level
except ImportError:
pytest.skip("ScanRequest not available")
def test_scan_status_creation(self):
"""Test ScanStatus creation"""
try:
from web_ui.backend.main import ScanStatus
status = ScanStatus(
scan_id="scan-001",
status="running",
progress=50.0,
current_step=10,
total_steps=50,
findings_count=5,
start_time=datetime.now().isoformat(),
end_time=None,
error_message=None,
)
assert status.scan_id == "scan-001"
assert status.status == "running"
assert status.progress == 50.0
except ImportError:
pytest.skip("ScanStatus not available")
def test_scan_status_statuses(self):
"""Test different scan statuses"""
try:
from web_ui.backend.main import ScanStatus
statuses = ["pending", "running", "completed", "failed"]
for status_val in statuses:
status = ScanStatus(
scan_id="scan-001",
status=status_val,
progress=50.0,
current_step=1,
total_steps=10,
findings_count=0,
start_time=datetime.now().isoformat(),
)
assert status.status == status_val
except ImportError:
pytest.skip("ScanStatus not available")
def test_finding_creation(self):
"""Test Finding creation"""
try:
from web_ui.backend.main import Finding
finding = Finding(
id="finding-001",
type="vulnerability",
severity="HIGH",
title="Test Finding",
description="Test description",
target="example.com",
evidence={"key": "value"},
risk_score={"score": 7.5},
timestamp=datetime.now().isoformat(),
)
assert finding.id == "finding-001"
assert finding.severity == "HIGH"
except ImportError:
pytest.skip("Finding not available")
def test_finding_severities(self):
"""Test different finding severities"""
try:
from web_ui.backend.main import Finding
severities = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"]
for sev in severities:
finding = Finding(
id="finding-001",
type="vulnerability",
severity=sev,
title=f"{sev} Finding",
description="Test",
target="example.com",
timestamp=datetime.now().isoformat(),
)
assert finding.severity == sev
except ImportError:
pytest.skip("Finding not available")
def test_finding_optional_fields(self):
"""Test Finding with optional fields"""
try:
from web_ui.backend.main import Finding
finding = Finding(
id="finding-001",
type="info",
severity="LOW",
title="Simple Finding",
description="No optional fields",
target="example.com",
timestamp=datetime.now().isoformat(),
)
assert finding.evidence is None
assert finding.risk_score is None
except ImportError:
pytest.skip("Finding not available")
def test_dashboard_stats_creation(self):
"""Test DashboardStats creation"""
try:
from web_ui.backend.main import DashboardStats
stats = DashboardStats(
total_scans=10,
active_scans=2,
completed_scans=7,
failed_scans=1,
total_findings=25,
critical_findings=3,
high_findings=8,
tools_used=["nmap", "nuclei"],
)
assert stats.total_scans == 10
assert stats.active_scans == 2
assert stats.critical_findings == 3
assert len(stats.tools_used) == 2
except ImportError:
pytest.skip("DashboardStats not available")
def test_dashboard_stats_empty(self):
"""Test DashboardStats with empty values"""
try:
from web_ui.backend.main import DashboardStats
stats = DashboardStats(
total_scans=0,
active_scans=0,
completed_scans=0,
failed_scans=0,
total_findings=0,
critical_findings=0,
high_findings=0,
tools_used=[],
)
assert stats.total_scans == 0
assert stats.tools_used == []
except ImportError:
pytest.skip("DashboardStats not available")
# ============================================================================
# SCAN MANAGER TESTS
# ============================================================================
class TestScanManager:
"""Tests für ScanManager"""
def test_scan_manager_init(self):
"""Test ScanManager initialization"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
assert manager.active_scans == {}
assert manager.scan_history == []
assert manager.clients == []
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_start_scan(self):
"""Test starting a new scan"""
try:
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="example.com")
await manager.start_scan(scan_id, request)
assert scan_id in manager.active_scans
scan = manager.active_scans[scan_id]
assert scan["id"] == scan_id
assert scan["status"] == "pending"
assert scan["progress"] == 0.0
assert scan["request"].target == "example.com"
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_start_scan_multiple(self):
"""Test starting multiple scans"""
try:
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_ids = []
for i in range(3):
scan_id = str(uuid.uuid4())
request = ScanRequest(target=f"target{i}.com")
await manager.start_scan(scan_id, request)
scan_ids.append(scan_id)
assert len(manager.active_scans) == 3
for sid in scan_ids:
assert sid in manager.active_scans
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_update_progress(self):
"""Test updating scan progress"""
try:
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="example.com")
await manager.start_scan(scan_id, request)
await manager.update_progress(scan_id, 50.0, 5, "Test message")
scan = manager.active_scans[scan_id]
assert scan["progress"] == 50.0
assert scan["current_step"] == 5
assert len(scan["logs"]) == 1
assert scan["logs"][0]["message"] == "Test message"
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_update_progress_no_message(self):
"""Test updating progress without message"""
try:
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="example.com")
await manager.start_scan(scan_id, request)
await manager.update_progress(scan_id, 25.0, 3)
scan = manager.active_scans[scan_id]
assert scan["progress"] == 25.0
assert len(scan["logs"]) == 0
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_update_progress_invalid_scan(self):
"""Test updating progress for non-existent scan"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
# Should not raise error
await manager.update_progress("invalid-id", 50.0, 5, "Test")
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_add_finding(self):
"""Test adding a finding"""
try:
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="example.com")
await manager.start_scan(scan_id, request)
finding = {"id": "f001", "severity": "HIGH", "title": "Test"}
await manager.add_finding(scan_id, finding)
scan = manager.active_scans[scan_id]
assert len(scan["findings"]) == 1
assert scan["findings"][0]["id"] == "f001"
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_add_multiple_findings(self):
"""Test adding multiple findings"""
try:
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="example.com")
await manager.start_scan(scan_id, request)
for i in range(5):
finding = {"id": f"f00{i}", "severity": "MEDIUM"}
await manager.add_finding(scan_id, finding)
scan = manager.active_scans[scan_id]
assert len(scan["findings"]) == 5
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_add_finding_invalid_scan(self):
"""Test adding finding to non-existent scan"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
finding = {"id": "f001"}
# Should not raise error
await manager.add_finding("invalid-id", finding)
except ImportError:
pytest.skip("ScanManager not available")
def test_complete_scan_success(self):
"""Test completing a scan successfully"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="example.com")
# Use asyncio.run for the async start_scan
asyncio.run(manager.start_scan(scan_id, request))
manager.complete_scan(scan_id, success=True)
assert scan_id not in manager.active_scans
assert len(manager.scan_history) == 1
assert manager.scan_history[0]["status"] == "completed"
assert manager.scan_history[0]["end_time"] is not None
except ImportError:
pytest.skip("ScanManager not available")
def test_complete_scan_failure(self):
"""Test completing a scan with failure"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="example.com")
asyncio.run(manager.start_scan(scan_id, request))
manager.complete_scan(scan_id, success=False, error="Test error")
assert scan_id not in manager.active_scans
assert len(manager.scan_history) == 1
assert manager.scan_history[0]["status"] == "failed"
assert manager.scan_history[0]["error"] == "Test error"
except ImportError:
pytest.skip("ScanManager not available")
def test_complete_scan_invalid_id(self):
"""Test completing non-existent scan"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
# Should not raise error
manager.complete_scan("invalid-id", success=True)
except ImportError:
pytest.skip("ScanManager not available")
def test_get_scan_status_active(self):
"""Test getting status of active scan"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="example.com")
asyncio.run(manager.start_scan(scan_id, request))
status = manager.get_scan_status(scan_id)
assert status is not None
assert status["scan_id"] == scan_id
assert status["status"] == "pending"
except ImportError:
pytest.skip("ScanManager not available")
def test_get_scan_status_not_found(self):
"""Test getting status of non-existent scan"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
status = manager.get_scan_status("invalid-id")
assert status is None
except ImportError:
pytest.skip("ScanManager not available")
def test_get_all_scans_empty(self):
"""Test getting all scans when empty"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
scans = manager.get_all_scans()
assert scans == []
except ImportError:
pytest.skip("ScanManager not available")
def test_get_all_scans_with_data(self):
"""Test getting all scans with data"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="example.com")
asyncio.run(manager.start_scan(scan_id, request))
scans = manager.get_all_scans()
assert len(scans) == 1
assert scans[0]["scan_id"] == scan_id
assert scans[0]["target"] == "example.com"
except ImportError:
pytest.skip("ScanManager not available")
def test_get_dashboard_stats_empty(self):
"""Test dashboard stats when empty"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
stats = manager.get_dashboard_stats()
assert stats.total_scans == 0
assert stats.active_scans == 0
assert stats.total_findings == 0
assert stats.tools_used == []
except ImportError:
pytest.skip("ScanManager not available")
def test_get_dashboard_stats_with_findings(self):
"""Test dashboard stats with findings"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
# Create scan with findings
scan_id = str(uuid.uuid4())
request = ScanRequest(target="example.com")
asyncio.run(manager.start_scan(scan_id, request))
# Add findings
findings = [
{"id": "f1", "severity": "CRITICAL", "tool": "nmap"},
{"id": "f2", "severity": "HIGH", "tool": "nuclei"},
{"id": "f3", "severity": "HIGH", "tool": "nmap"},
{"id": "f4", "severity": "MEDIUM"},
]
for f in findings:
asyncio.run(manager.add_finding(scan_id, f))
stats = manager.get_dashboard_stats()
assert stats.total_scans == 1
assert stats.active_scans == 1
assert stats.total_findings == 4
assert stats.critical_findings == 1
assert stats.high_findings == 2
assert set(stats.tools_used) == {"nmap", "nuclei"}
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_connect_client(self, mock_websocket):
"""Test connecting a WebSocket client"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
await manager.connect_client(mock_websocket)
assert len(manager.clients) == 1
mock_websocket.accept.assert_called_once()
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_disconnect_client(self, mock_websocket):
"""Test disconnecting a WebSocket client"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
await manager.connect_client(mock_websocket)
await manager.disconnect_client(mock_websocket)
assert len(manager.clients) == 0
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_disconnect_client_not_connected(self, mock_websocket):
"""Test disconnecting a client that was never connected"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
# Should not raise error
await manager.disconnect_client(mock_websocket)
assert len(manager.clients) == 0
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_broadcast(self, mock_websocket):
"""Test broadcasting message to clients"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
await manager.connect_client(mock_websocket)
message = {"type": "test", "data": "hello"}
await manager.broadcast(message)
mock_websocket.send_json.assert_called_with(message)
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_broadcast_multiple_clients(self):
"""Test broadcasting to multiple clients"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
ws1 = MagicMock()
ws1.accept = AsyncMock()
ws1.send_json = AsyncMock()
ws2 = MagicMock()
ws2.accept = AsyncMock()
ws2.send_json = AsyncMock()
await manager.connect_client(ws1)
await manager.connect_client(ws2)
message = {"type": "test"}
await manager.broadcast(message)
ws1.send_json.assert_called_with(message)
ws2.send_json.assert_called_with(message)
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_broadcast_with_disconnected_client(self, mock_websocket_send_error):
"""Test broadcast handles disconnected clients"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
await manager.connect_client(mock_websocket_send_error)
message = {"type": "test"}
await manager.broadcast(message)
# Client should be removed
assert len(manager.clients) == 0
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_broadcast_no_clients(self):
"""Test broadcasting when no clients connected"""
try:
from web_ui.backend.main import ScanManager
manager = ScanManager()
# Should not raise error
await manager.broadcast({"type": "test"})
except ImportError:
pytest.skip("ScanManager not available")
# ============================================================================
# API ENDPOINT TESTS
# ============================================================================
class TestAPIEndpoints:
"""Tests für API Endpoints"""
@pytest.fixture
def client(self):
"""Create test client"""
try:
from web_ui.backend.main import app
return TestClient(app)
except ImportError:
pytest.skip("Web UI app not available")
def test_health_check(self, client):
"""Test health check endpoint"""
response = client.get("/api/health")
assert response.status_code == 200
data = response.json()
assert data["status"] == "healthy"
assert "version" in data
def test_dashboard_stats_empty(self, client):
"""Test dashboard stats endpoint when empty"""
response = client.get("/api/dashboard/stats")
assert response.status_code == 200
data = response.json()
assert data["total_scans"] == 0
assert data["active_scans"] == 0
def test_get_all_scans_empty(self, client):
"""Test getting all scans when empty"""
response = client.get("/api/scans")
assert response.status_code == 200
data = response.json()
assert data == []
def test_create_scan_success(self, client, mock_scan_request):
"""Test creating a new scan"""
response = client.post("/api/scans", json=mock_scan_request)
assert response.status_code == 200
data = response.json()
assert "scan_id" in data
assert data["status"] == "started"
assert "example.com" in data["message"]
def test_create_scan_minimal(self, client, mock_scan_request_minimal):
"""Test creating scan with minimal data"""
response = client.post("/api/scans", json=mock_scan_request_minimal)
assert response.status_code == 200
data = response.json()
assert "scan_id" in data
def test_create_scan_various_types(self, client):
"""Test creating scans with different types"""
scan_types = ["quick", "standard", "comprehensive"]
for scan_type in scan_types:
request = {"target": "test.com", "scan_type": scan_type}
response = client.post("/api/scans", json=request)
assert response.status_code == 200
def test_create_scan_various_safety_levels(self, client):
"""Test creating scans with different safety levels"""
safety_levels = [
"read_only",
"non_destructive",
"destructive",
"exploit",
]
for level in safety_levels:
request = {"target": "test.com", "safety_level": level}
response = client.post("/api/scans", json=request)
assert response.status_code == 200
def test_create_scan_invalid_json(self, client):
"""Test creating scan with invalid JSON"""
response = client.post("/api/scans", content="invalid json")
assert response.status_code == 422
def test_create_scan_missing_target(self, client):
"""Test creating scan without target"""
request = {"scan_type": "quick"}
response = client.post("/api/scans", json=request)
assert response.status_code == 422
def test_get_scan_not_found(self, client):
"""Test getting non-existent scan"""
response = client.get("/api/scans/invalid-id")
assert response.status_code == 404
assert "not found" in response.json()["detail"].lower()
def test_get_scan_status_not_found(self, client):
"""Test getting status of non-existent scan"""
response = client.get("/api/scans/invalid-id/status")
assert response.status_code == 404
def test_get_scan_findings_not_found(self, client):
"""Test getting findings of non-existent scan"""
response = client.get("/api/scans/invalid-id/findings")
assert response.status_code == 404
def test_get_scan_logs_not_found(self, client):
"""Test getting logs of non-existent scan"""
response = client.get("/api/scans/invalid-id/logs")
assert response.status_code == 404
def test_cancel_scan_not_found(self, client):
"""Test cancelling non-existent scan"""
response = client.delete("/api/scans/invalid-id")
assert response.status_code == 404
def test_create_and_get_scan(self, client):
"""Test creating and then retrieving a scan"""
# Create scan
create_response = client.post("/api/scans", json={"target": "test.com"})
assert create_response.status_code == 200
scan_id = create_response.json()["scan_id"]
# Get scan
get_response = client.get(f"/api/scans/{scan_id}")
assert get_response.status_code == 200
data = get_response.json()
assert data["id"] == scan_id
assert data["request"]["target"] == "test.com"
def test_create_and_get_scan_status(self, client):
"""Test creating and getting scan status"""
# Create scan
create_response = client.post("/api/scans", json={"target": "test.com"})
scan_id = create_response.json()["scan_id"]
# Get status
status_response = client.get(f"/api/scans/{scan_id}/status")
assert status_response.status_code == 200
data = status_response.json()
assert data["scan_id"] == scan_id
assert "status" in data
assert "progress" in data
def test_create_and_cancel_scan(self, client):
"""Test creating and cancelling a scan"""
# Create scan
create_response = client.post("/api/scans", json={"target": "test.com"})
scan_id = create_response.json()["scan_id"]
# Cancel scan
cancel_response = client.delete(f"/api/scans/{scan_id}")
assert cancel_response.status_code == 200
assert "cancelled" in cancel_response.json()["message"].lower()
def test_cancel_completed_scan(self, client):
"""Test cancelling an already completed scan"""
# Create and cancel once
create_response = client.post("/api/scans", json={"target": "test.com"})
scan_id = create_response.json()["scan_id"]
client.delete(f"/api/scans/{scan_id}")
# Try to cancel again
response = client.delete(f"/api/scans/{scan_id}")
assert response.status_code == 404
def test_get_scan_findings_empty(self, client):
"""Test getting empty findings list"""
# Create scan
create_response = client.post("/api/scans", json={"target": "test.com"})
scan_id = create_response.json()["scan_id"]
# Get findings
response = client.get(f"/api/scans/{scan_id}/findings")
assert response.status_code == 200
assert response.json() == []
def test_get_scan_logs_empty(self, client):
"""Test getting empty logs list"""
# Create scan
create_response = client.post("/api/scans", json={"target": "test.com"})
scan_id = create_response.json()["scan_id"]
# Get logs
response = client.get(f"/api/scans/{scan_id}/logs")
assert response.status_code == 200
assert response.json() == []
def test_get_all_scans_with_active(self, client):
"""Test getting all scans with active scan"""
# Create multiple scans
scan_ids = []
for i in range(3):
response = client.post("/api/scans", json={"target": f"test{i}.com"})
scan_ids.append(response.json()["scan_id"])
# Get all scans
response = client.get("/api/scans")
assert response.status_code == 200
data = response.json()
assert len(data) == 3
def test_dashboard_stats_with_scans(self, client):
"""Test dashboard stats with active scans"""
# Create scans
for i in range(3):
client.post("/api/scans", json={"target": f"test{i}.com"})
# Get stats
response = client.get("/api/dashboard/stats")
assert response.status_code == 200
data = response.json()
assert data["total_scans"] == 3
assert data["active_scans"] == 3
# ============================================================================
# WEBSOCKET TESTS
# ============================================================================
class TestWebSocket:
"""Tests für WebSocket Handler"""
@pytest.fixture
def client(self):
"""Create test client"""
try:
from web_ui.backend.main import app
return TestClient(app)
except ImportError:
pytest.skip("Web UI app not available")
def test_websocket_connection(self, client):
"""Test WebSocket connection"""
try:
with client.websocket_connect("/ws") as websocket:
# Send ping
websocket.send_text(json.dumps({"type": "ping"}))
# Receive pong
data = websocket.receive_json()
assert data["type"] == "pong"
except Exception as e:
pytest.skip(f"WebSocket test skipped: {e}")
def test_websocket_multiple_messages(self, client):
"""Test WebSocket with multiple messages"""
try:
with client.websocket_connect("/ws") as websocket:
for i in range(3):
websocket.send_text(json.dumps({"type": "ping"}))
data = websocket.receive_json()
assert data["type"] == "pong"
except Exception as e:
pytest.skip(f"WebSocket test skipped: {e}")
def test_websocket_invalid_message(self, client):
"""Test WebSocket with invalid message"""
try:
with client.websocket_connect("/ws") as websocket:
# Send invalid JSON
websocket.send_text("invalid json")
# Should handle gracefully
except Exception:
pass # Expected to handle or disconnect
def test_websocket_different_message_types(self, client):
"""Test WebSocket with different message types"""
try:
with client.websocket_connect("/ws") as websocket:
# Send different types
message_types = ["ping", "subscribe", "unknown"]
for msg_type in message_types:
websocket.send_text(json.dumps({"type": msg_type}))
# Should not raise error
except Exception as e:
pytest.skip(f"WebSocket test skipped: {e}")
@pytest.mark.asyncio
async def test_websocket_connect_handler(self, mock_websocket):
"""Test WebSocket connect handler directly"""
try:
from web_ui.backend.main import scan_manager
await scan_manager.connect_client(mock_websocket)
assert mock_websocket in scan_manager.clients
mock_websocket.accept.assert_called_once()
except ImportError:
pytest.skip("WebSocket handler not available")
@pytest.mark.asyncio
async def test_websocket_disconnect_handler(self, mock_websocket):
"""Test WebSocket disconnect handler"""
try:
from web_ui.backend.main import scan_manager
await scan_manager.connect_client(mock_websocket)
await scan_manager.disconnect_client(mock_websocket)
assert mock_websocket not in scan_manager.clients
except ImportError:
pytest.skip("WebSocket handler not available")
# ============================================================================
# BACKGROUND TASK TESTS
# ============================================================================
class TestBackgroundTasks:
"""Tests für Background Tasks"""
@pytest.mark.asyncio
async def test_run_scan_function(self):
"""Test run_scan background function"""
try:
import asyncio
from web_ui.backend.main import ScanRequest, run_scan, scan_manager
# Create a scan
scan_id = str(uuid.uuid4())
request = ScanRequest(target="example.com")
await scan_manager.start_scan(scan_id, request)
# Mock the agent to avoid full execution
with patch("web_ui.backend.main.AutonomousAgent") as mock_agent_class:
mock_agent = MagicMock()
mock_agent.run = AsyncMock(return_value={"findings": [{"severity": "HIGH", "title": "Test"}]})
mock_agent_class.return_value = mock_agent
with patch("web_ui.backend.main.RiskScorer") as mock_risk:
mock_risk_scorer = MagicMock()
mock_risk_scorer.calculate.return_value = MagicMock(to_dict=lambda: {"score": 7.5})
mock_risk.return_value = mock_risk_scorer
# Run with timeout to avoid hanging
await asyncio.wait_for(run_scan(scan_id, request), timeout=5.0)
except ImportError:
pytest.skip("Background task not available")
except asyncio.TimeoutError:
pass # Expected with mocks
@pytest.mark.asyncio
async def test_run_scan_safety_levels(self):
"""Test run_scan with different safety levels"""
try:
from web_ui.backend.main import ScanRequest, run_scan
safety_levels = [
"read_only",
"non_destructive",
"destructive",
"exploit",
]
for level in safety_levels:
request = ScanRequest(target="test.com", safety_level=level)
# Just verify it doesn't crash on safety level mapping
assert request.safety_level == level
except ImportError:
pytest.skip("Background task not available")
# ============================================================================
# STATIC FILES TESTS
# ============================================================================
class TestStaticFiles:
"""Tests für Static File Serving"""
@pytest.fixture
def client(self):
"""Create test client"""
try:
from web_ui.backend.main import app
return TestClient(app)
except ImportError:
pytest.skip("Web UI app not available")
def test_static_files_mount(self, client):
"""Test static files are mounted"""
# Static files endpoint exists
# May return 404 if build directory doesn't exist, but shouldn't crash
response = client.get("/static/test.css")
# Either 200 (if file exists) or 404 (if not) is acceptable
assert response.status_code in [200, 404, 307]
def test_root_endpoint(self, client):
"""Test root endpoint for frontend"""
response = client.get("/")
# May return 200 (if index.html exists) or 404 (if not)
assert response.status_code in [200, 404]
def test_frontend_routes(self, client):
"""Test frontend route catch-all"""
routes = ["/dashboard", "/scans", "/reports", "/settings"]
for route in routes:
response = client.get(route)
# Either serves index.html or 404
assert response.status_code in [200, 404]
# ============================================================================
# INTEGRATION TESTS
# ============================================================================
class TestIntegration:
"""Integration Tests"""
@pytest.fixture
def client(self):
"""Create test client"""
try:
from web_ui.backend.main import app
return TestClient(app)
except ImportError:
pytest.skip("Web UI app not available")
def test_full_scan_workflow(self, client):
"""Test complete scan workflow"""
# 1. Create scan
create_response = client.post(
"/api/scans",
json={"target": "integration-test.com", "scan_type": "quick"},
)
assert create_response.status_code == 200
scan_id = create_response.json()["scan_id"]
# 2. Check dashboard stats
stats_response = client.get("/api/dashboard/stats")
assert stats_response.status_code == 200
stats = stats_response.json()
assert stats["total_scans"] >= 1
assert stats["active_scans"] >= 1
# 3. Get scan details
scan_response = client.get(f"/api/scans/{scan_id}")
assert scan_response.status_code == 200
# 4. Get scan status
status_response = client.get(f"/api/scans/{scan_id}/status")
assert status_response.status_code == 200
# 5. Get all scans
all_scans_response = client.get("/api/scans")
assert all_scans_response.status_code == 200
# 6. Cancel scan
cancel_response = client.delete(f"/api/scans/{scan_id}")
assert cancel_response.status_code == 200
def test_multiple_scans_workflow(self, client):
"""Test workflow with multiple scans"""
scan_ids = []
targets = ["target1.com", "target2.com", "target3.com"]
# Create scans
for target in targets:
response = client.post("/api/scans", json={"target": target})
scan_ids.append(response.json()["scan_id"])
# Verify all scans exist
all_scans = client.get("/api/scans").json()
assert len(all_scans) >= 3
# Cancel all
for scan_id in scan_ids:
response = client.delete(f"/api/scans/{scan_id}")
assert response.status_code == 200
def test_cors_headers(self, client):
"""Test CORS headers are present"""
response = client.options("/api/health")
# CORS should be configured
assert "access-control-allow-origin" in str(response.headers).lower() or response.status_code == 200
def test_api_version_header(self, client):
"""Test API returns correct version info"""
response = client.get("/api/health")
assert response.status_code == 200
data = response.json()
assert "version" in data
# ============================================================================
# ERROR HANDLING TESTS
# ============================================================================
class TestErrorHandling:
"""Tests für Error Handling"""
@pytest.fixture
def client(self):
"""Create test client"""
try:
from web_ui.backend.main import app
return TestClient(app)
except ImportError:
pytest.skip("Web UI app not available")
def test_404_response_format(self, client):
"""Test 404 error response format"""
response = client.get("/api/scans/nonexistent-id")
assert response.status_code == 404
data = response.json()
assert "detail" in data
def test_422_validation_error(self, client):
"""Test validation error response"""
response = client.post("/api/scans", json={"invalid": "data"})
assert response.status_code == 422
def test_method_not_allowed(self, client):
"""Test method not allowed"""
response = client.post("/api/health")
assert response.status_code == 405
def test_invalid_json_payload(self, client):
"""Test invalid JSON payload"""
response = client.post(
"/api/scans",
content="not valid json",
headers={"Content-Type": "application/json"},
)
assert response.status_code == 422
def test_empty_payload(self, client):
"""Test empty payload"""
response = client.post("/api/scans", json={})
assert response.status_code == 422
def test_null_values_in_payload(self, client):
"""Test null values in payload"""
response = client.post("/api/scans", json={"target": None, "scan_type": "quick"})
assert response.status_code == 422
# ============================================================================
# LIFESPAN TESTS
# ============================================================================
class TestLifespan:
"""Tests für Application Lifespan"""
def test_lifespan_import(self):
"""Test lifespan function exists"""
try:
from web_ui.backend.main import lifespan
assert lifespan is not None
except ImportError:
pytest.skip("Lifespan not available")
@pytest.mark.asyncio
async def test_lifespan_context_manager(self):
"""Test lifespan context manager"""
try:
from web_ui.backend.main import app, lifespan
async with lifespan(app):
pass # App should start and stop cleanly
except ImportError:
pytest.skip("Lifespan not available")
# ============================================================================
# GLOBAL STATE TESTS
# ============================================================================
class TestGlobalState:
"""Tests für Global State"""
def test_scan_manager_singleton(self):
"""Test that scan_manager is a singleton"""
try:
# Should be the same instance
from web_ui.backend.main import scan_manager
from web_ui.backend.main import scan_manager as sm2
assert scan_manager is sm2
except ImportError:
pytest.skip("Scan manager not available")
def test_app_instance(self):
"""Test FastAPI app instance"""
try:
from web_ui.backend.main import app
assert app is not None
assert app.title == "Zen AI Pentest Web UI"
assert app.version == "2.0.0"
except ImportError:
pytest.skip("App not available")
# ============================================================================
# ADDITIONAL DASHBOARD STATS TESTS
# ============================================================================
class TestDashboardStatsAdditional:
"""Additional Dashboard Stats Tests"""
def test_dashboard_stats_critical_only(self):
"""Test dashboard stats with only critical findings"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
asyncio.run(manager.start_scan(scan_id, request))
# Add only critical findings
for i in range(5):
finding = {
"id": f"f{i}",
"severity": "CRITICAL",
"tool": "tool1",
}
asyncio.run(manager.add_finding(scan_id, finding))
stats = manager.get_dashboard_stats()
assert stats.critical_findings == 5
assert stats.high_findings == 0
except ImportError:
pytest.skip("ScanManager not available")
def test_dashboard_stats_high_only(self):
"""Test dashboard stats with only high findings"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
asyncio.run(manager.start_scan(scan_id, request))
for i in range(3):
finding = {"id": f"f{i}", "severity": "HIGH"}
asyncio.run(manager.add_finding(scan_id, finding))
stats = manager.get_dashboard_stats()
assert stats.critical_findings == 0
assert stats.high_findings == 3
except ImportError:
pytest.skip("ScanManager not available")
def test_dashboard_stats_mixed_findings(self):
"""Test dashboard stats with mixed severity findings"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
asyncio.run(manager.start_scan(scan_id, request))
severities = ["CRITICAL", "HIGH", "HIGH", "MEDIUM", "LOW", "INFO"]
for i, sev in enumerate(severities):
finding = {"id": f"f{i}", "severity": sev}
asyncio.run(manager.add_finding(scan_id, finding))
stats = manager.get_dashboard_stats()
assert stats.total_findings == 6
assert stats.critical_findings == 1
assert stats.high_findings == 2
except ImportError:
pytest.skip("ScanManager not available")
def test_dashboard_stats_tools_unique(self):
"""Test that tools_used contains unique tools"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
asyncio.run(manager.start_scan(scan_id, request))
# Add duplicate tool entries
for i in range(5):
finding = {"id": f"f{i}", "severity": "HIGH", "tool": "nmap"}
asyncio.run(manager.add_finding(scan_id, finding))
stats = manager.get_dashboard_stats()
assert stats.tools_used == ["nmap"] # Should be unique
except ImportError:
pytest.skip("ScanManager not available")
def test_dashboard_stats_multiple_tools(self):
"""Test dashboard stats with multiple different tools"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
asyncio.run(manager.start_scan(scan_id, request))
tools = ["nmap", "nuclei", "sqlmap", "gobuster"]
for i, tool in enumerate(tools):
finding = {"id": f"f{i}", "severity": "MEDIUM", "tool": tool}
asyncio.run(manager.add_finding(scan_id, finding))
stats = manager.get_dashboard_stats()
assert set(stats.tools_used) == set(tools)
except ImportError:
pytest.skip("ScanManager not available")
# ============================================================================
# SCAN STATUS STATE TESTS
# ============================================================================
class TestScanStatusStates:
"""Tests for different scan status states"""
def test_scan_pending_state(self):
"""Test scan in pending state"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
asyncio.run(manager.start_scan(scan_id, request))
status = manager.get_scan_status(scan_id)
assert status["status"] == "pending"
assert status["progress"] == 0.0
assert status["end_time"] is None
except ImportError:
pytest.skip("ScanManager not available")
def test_scan_running_state(self):
"""Test scan in running state"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
asyncio.run(manager.start_scan(scan_id, request))
# Simulate status update to running
manager.active_scans[scan_id]["status"] = "running"
status = manager.get_scan_status(scan_id)
assert status["status"] == "running"
except ImportError:
pytest.skip("ScanManager not available")
def test_scan_completed_state(self):
"""Test scan in completed state"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
asyncio.run(manager.start_scan(scan_id, request))
manager.complete_scan(scan_id, success=True)
assert scan_id not in manager.active_scans
assert manager.scan_history[0]["status"] == "completed"
except ImportError:
pytest.skip("ScanManager not available")
def test_scan_failed_state(self):
"""Test scan in failed state"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
asyncio.run(manager.start_scan(scan_id, request))
manager.complete_scan(scan_id, success=False, error="Test failure")
assert manager.scan_history[0]["status"] == "failed"
assert manager.scan_history[0]["error"] == "Test failure"
except ImportError:
pytest.skip("ScanManager not available")
def test_scan_findings_count(self):
"""Test scan findings count in status"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
asyncio.run(manager.start_scan(scan_id, request))
for i in range(10):
finding = {"id": f"f{i}", "severity": "LOW"}
asyncio.run(manager.add_finding(scan_id, finding))
status = manager.get_scan_status(scan_id)
assert status["findings_count"] == 10
except ImportError:
pytest.skip("ScanManager not available")
# ============================================================================
# SCAN LOGS TESTS
# ============================================================================
class TestScanLogs:
"""Tests for scan logs"""
def test_scan_logs_initially_empty(self):
"""Test that scan logs are initially empty"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
asyncio.run(manager.start_scan(scan_id, request))
scan = manager.active_scans[scan_id]
assert scan["logs"] == []
except ImportError:
pytest.skip("ScanManager not available")
@pytest.mark.asyncio
async def test_scan_logs_with_updates(self):
"""Test that logs are populated with progress updates"""
try:
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
await manager.start_scan(scan_id, request)
await manager.update_progress(scan_id, 25, 1, "Started reconnaissance")
await manager.update_progress(scan_id, 50, 2, "Found open ports")
await manager.update_progress(scan_id, 75, 3, "Completed analysis")
scan = manager.active_scans[scan_id]
assert len(scan["logs"]) == 3
assert scan["logs"][0]["message"] == "Started reconnaissance"
assert scan["logs"][1]["message"] == "Found open ports"
assert scan["logs"][2]["message"] == "Completed analysis"
except ImportError:
pytest.skip("ScanManager not available")
def test_scan_logs_timestamps(self):
"""Test that logs have timestamps"""
try:
import asyncio
from web_ui.backend.main import ScanManager, ScanRequest
manager = ScanManager()
scan_id = str(uuid.uuid4())
request = ScanRequest(target="test.com")
asyncio.run(manager.start_scan(scan_id, request))
asyncio.run(manager.update_progress(scan_id, 50, 1, "Test message"))
scan = manager.active_scans[scan_id]
assert "timestamp" in scan["logs"][0]
assert scan["logs"][0]["timestamp"] is not None
except ImportError:
pytest.skip("ScanManager not available")
# ============================================================================
# ADDITIONAL API ENDPOINT TESTS
# ============================================================================
class TestAPIAdditional:
"""Additional API endpoint tests"""
@pytest.fixture
def client(self):
"""Create test client"""
try:
from web_ui.backend.main import app
return TestClient(app)
except ImportError:
pytest.skip("Web UI app not available")
def test_create_scan_with_scope(self, client):
"""Test creating scan with scope"""
response = client.post(
"/api/scans",
json={
"target": "scoped-test.com",
"scope": {
"ports": [80, 443, 8080],
"paths": ["/api", "/admin"],
"exclude": ["/logout"],
},
},
)
assert response.status_code == 200
data = response.json()
assert "scan_id" in data
def test_create_scan_with_goal(self, client):
"""Test creating scan with specific goal"""
response = client.post(
"/api/scans",
json={
"target": "goal-test.com",
"goal": "Find SQL injection vulnerabilities",
},
)
assert response.status_code == 200
def test_scan_target_validation(self, client):
"""Test various target formats"""
targets = [
"example.com",
"sub.example.com",
"192.168.1.1",
"test-site.org",
]
for target in targets:
response = client.post("/api/scans", json={"target": target})
assert response.status_code == 200, f"Failed for target: {target}"
def test_get_scan_response_structure(self, client):
"""Test scan response has correct structure"""
# Create scan
create_resp = client.post("/api/scans", json={"target": "struct-test.com"})
scan_id = create_resp.json()["scan_id"]
# Get scan details
get_resp = client.get(f"/api/scans/{scan_id}")
assert get_resp.status_code == 200
data = get_resp.json()
# Check required fields
assert "id" in data
assert "request" in data
assert "status" in data
assert "findings" in data
assert "logs" in data
assert "start_time" in data
def test_get_scan_status_structure(self, client):
"""Test scan status response structure"""
create_resp = client.post("/api/scans", json={"target": "status-test.com"})
scan_id = create_resp.json()["scan_id"]
status_resp = client.get(f"/api/scans/{scan_id}/status")
assert status_resp.status_code == 200
data = status_resp.json()
required_fields = [
"scan_id",
"status",
"progress",
"current_step",
"total_steps",
"findings_count",
"start_time",
]
for field in required_fields:
assert field in data, f"Missing field: {field}"
def test_dashboard_stats_structure(self, client):
"""Test dashboard stats response structure"""
response = client.get("/api/dashboard/stats")
assert response.status_code == 200
data = response.json()
required_fields = [
"total_scans",
"active_scans",
"completed_scans",
"failed_scans",
"total_findings",
"critical_findings",
"high_findings",
"tools_used",
]
for field in required_fields:
assert field in data, f"Missing field: {field}"
# ============================================================================
# REPORT GENERATION TESTS
# ============================================================================
class TestReportGeneration:
"""Tests for report generation features"""
@pytest.fixture
def client(self):
"""Create test client"""
try:
from web_ui.backend.main import app
return TestClient(app)
except ImportError:
pytest.skip("Web UI app not available")
def test_findings_format(self, client):
"""Test findings response format"""
# Create scan
create_resp = client.post("/api/scans", json={"target": "finding-test.com"})
scan_id = create_resp.json()["scan_id"]
# Get findings
findings_resp = client.get(f"/api/scans/{scan_id}/findings")
assert findings_resp.status_code == 200
assert isinstance(findings_resp.json(), list)
def test_findings_with_data(self, client, mock_finding):
"""Test findings with data"""
try:
import asyncio
from web_ui.backend.main import ScanRequest, scan_manager
# Create scan and add finding directly
scan_id = str(uuid.uuid4())
request = ScanRequest(target="finding-test.com")
asyncio.run(scan_manager.start_scan(scan_id, request))
asyncio.run(scan_manager.add_finding(scan_id, mock_finding))
# Get findings via API
findings_resp = client.get(f"/api/scans/{scan_id}/findings")
assert findings_resp.status_code == 200
findings = findings_resp.json()
assert len(findings) == 1
assert findings[0]["id"] == "finding-001"
except ImportError:
pytest.skip("Scan manager not available")
def test_logs_format(self, client):
"""Test logs response format"""
create_resp = client.post("/api/scans", json={"target": "logs-test.com"})
scan_id = create_resp.json()["scan_id"]
logs_resp = client.get(f"/api/scans/{scan_id}/logs")
assert logs_resp.status_code == 200
assert isinstance(logs_resp.json(), list)
def test_all_scans_format(self, client):
"""Test all scans response format"""
response = client.get("/api/scans")
assert response.status_code == 200
assert isinstance(response.json(), list)
if __name__ == "__main__":
pytest.main([__file__, "-v", "--tb=short"])
"""
Web UI Backend Unit Tests
=========================
100+ Tests für das Web UI Backend:
- API Endpoints für Web UI
- Dashboard Daten
- Report Generation
- WebSocket Handlers
Run: pytest tests/unit/test_web_ui.py -v --tb=short
"""
import json
import os
import sys
import uuid
from datetime import datetime
from unittest.mock import AsyncMock, MagicMock, Mock, PropertyMock, patch
import pytest
from fastapi import WebSocketDisconnect
from starlette.testclient import TestClient
from starlette.websockets import WebSocket
# Setup environment BEFORE any imports
os.environ["ADMIN_PASSWORD"] = "test_password"
os.environ["ADMIN_USERNAME"] = "admin"
os.environ["JWT_SECRET_KEY"] = "test-secret-key-for-testing-only"
os.environ["DATABASE_URL"] = "sqlite:///:memory:"
os.environ["REDIS_URL"] = "redis://localhost:6379/0"
os.environ["CORS_ORIGINS"] = "http://localhost:3000"
os.environ["TESTING"] = "true"
# Add project to path
project_root = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
sys.path.insert(0, str(project_root))
# ============================================================================
# FIXTURES
# ============================================================================
def mock_scan_request():
"""Mock scan request data"""
return {
"target": "example.com",
"goal": "Test security assessment",
"scan_type": "comprehensive",
"safety_level": "non_destructive",
"scope": {"ports": [80, 443]},
}
def mock_scan_request_minimal():
"""Minimal scan request with defaults"""
return {"target": "test.com"}
def mock_finding():
"""Mock finding data"""
return {
"id": "finding-001",
"type": "vulnerability",
"severity": "HIGH",
"title": "SQL Injection",
"description": "SQL injection vulnerability found",
"target": "example.com",
"evidence": {"payload": "' OR 1=1--"},
"risk_score": {"score": 8.5, "severity": "HIGH"},
"timestamp": datetime.now().isoformat(),
}
def mock_finding_critical():
"""Mock critical finding"""
return {
"id": "finding-002",
"type": "vulnerability",
"severity": "CRITICAL",
"title": "Remote Code Execution",
"description": "RCE vulnerability found",
"target": "example.com",
"tool": "nuclei",
"evidence": {"payload": ";whoami"},
"risk_score": {"score": 9.8, "severity": "CRITICAL"},
"timestamp": datetime.now().isoformat(),
}
def mock_finding_medium():
"""Mock medium finding"""
return {
"id": "finding-003",
"type": "info",
Xet Storage Details
- Size:
- 66.7 kB
- Xet hash:
- 6cb87599ac120c13acf91bf2fffbc19bad691b8f8ef7962c7438b92c8bf31bf2
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.