Buckets:

download
raw
34.7 kB
""" Comprehensive Tests for API Scan Model ======================================= Target: 90-100% Coverage for /api/models/scan.py Tests all scan states, configurations, and methods. Coverage targets: - ScanStatus enum: 100% - ScanType enum: 100% - Scan class: 90-100% - __init__: all parameters - find_one: classmethod - find_many: classmethod - save: async method - update: async method - to_response: serialization """ from datetime import datetime, timezone from unittest.mock import AsyncMock, MagicMock, patch import pytest # Import the module under test from api.models.scan import Scan, ScanStatus, ScanType # ============================================================================ # Test ScanStatus Enum # ============================================================================ class TestScanStatusEnum: """Test ScanStatus enumeration values and behavior.""" def test_scan_status_values(self): """Test all ScanStatus enum values are correct.""" assert ScanStatus.PENDING.value == "pending" assert ScanStatus.RUNNING.value == "running" assert ScanStatus.COMPLETED.value == "completed" assert ScanStatus.FAILED.value == "failed" assert ScanStatus.CANCELLED.value == "cancelled" def test_scan_status_enum_members(self): """Test ScanStatus enum members exist.""" assert hasattr(ScanStatus, "PENDING") assert hasattr(ScanStatus, "RUNNING") assert hasattr(ScanStatus, "COMPLETED") assert hasattr(ScanStatus, "FAILED") assert hasattr(ScanStatus, "CANCELLED") def test_scan_status_comparison(self): """Test ScanStatus enum comparison.""" assert ScanStatus.PENDING == ScanStatus.PENDING assert ScanStatus.RUNNING != ScanStatus.COMPLETED def test_scan_status_from_string(self): """Test creating ScanStatus from string value.""" status = ScanStatus("pending") assert status == ScanStatus.PENDING status = ScanStatus("running") assert status == ScanStatus.RUNNING status = ScanStatus("completed") assert status == ScanStatus.COMPLETED status = ScanStatus("failed") assert status == ScanStatus.FAILED status = ScanStatus("cancelled") assert status == ScanStatus.CANCELLED def test_scan_status_invalid_value(self): """Test ScanStatus with invalid value raises error.""" with pytest.raises(ValueError): ScanStatus("invalid_status") # ============================================================================ # Test ScanType Enum # ============================================================================ class TestScanTypeEnum: """Test ScanType enumeration values and behavior.""" def test_scan_type_values(self): """Test all ScanType enum values are correct.""" assert ScanType.PORT_SCAN.value == "port_scan" assert ScanType.VULNERABILITY.value == "vulnerability" assert ScanType.WEB_APP.value == "web_app" assert ScanType.NETWORK.value == "network" assert ScanType.COMPLIANCE.value == "compliance" assert ScanType.FULL.value == "full" def test_scan_type_enum_members(self): """Test ScanType enum members exist.""" assert hasattr(ScanType, "PORT_SCAN") assert hasattr(ScanType, "VULNERABILITY") assert hasattr(ScanType, "WEB_APP") assert hasattr(ScanType, "NETWORK") assert hasattr(ScanType, "COMPLIANCE") assert hasattr(ScanType, "FULL") def test_scan_type_comparison(self): """Test ScanType enum comparison.""" assert ScanType.PORT_SCAN == ScanType.PORT_SCAN assert ScanType.WEB_APP != ScanType.NETWORK def test_scan_type_from_string(self): """Test creating ScanType from string value.""" scan_type = ScanType("port_scan") assert scan_type == ScanType.PORT_SCAN scan_type = ScanType("vulnerability") assert scan_type == ScanType.VULNERABILITY scan_type = ScanType("web_app") assert scan_type == ScanType.WEB_APP scan_type = ScanType("network") assert scan_type == ScanType.NETWORK scan_type = ScanType("compliance") assert scan_type == ScanType.COMPLIANCE scan_type = ScanType("full") assert scan_type == ScanType.FULL def test_scan_type_invalid_value(self): """Test ScanType with invalid value raises error.""" with pytest.raises(ValueError): ScanType("invalid_type") # ============================================================================ # Test Scan Class - Initialization # ============================================================================ class TestScanInitialization: """Test Scan class initialization with various parameters.""" def test_scan_minimal_init(self): """Test Scan with minimal required parameters.""" scan = Scan(name="Test Scan", target="example.com") assert scan.name == "Test Scan" assert scan.target == "example.com" assert scan.scan_type == ScanType.PORT_SCAN # Default assert scan.status == ScanStatus.PENDING # Default assert scan.id == "scan-stub-id" assert scan.config == {} assert scan.schedule is None assert scan.created_by is None assert scan.progress == 0 assert scan.findings_count == 0 assert scan.error_message is None assert scan.started_at is None assert scan.completed_at is None assert isinstance(scan.created_at, datetime) def test_scan_full_init(self): """Test Scan with all parameters.""" config = {"ports": [80, 443], "threads": 10} schedule = {"cron": "0 0 * * *", "timezone": "UTC"} scan = Scan( name="Full Test Scan", target="192.168.1.1", scan_type=ScanType.VULNERABILITY, status=ScanStatus.RUNNING, created_by="user-123", config=config, schedule=schedule, ) assert scan.name == "Full Test Scan" assert scan.target == "192.168.1.1" assert scan.scan_type == ScanType.VULNERABILITY assert scan.status == ScanStatus.RUNNING assert scan.created_by == "user-123" assert scan.config == config assert scan.schedule == schedule def test_scan_all_statuses_init(self): """Test Scan initialization with all possible statuses.""" statuses = [ ScanStatus.PENDING, ScanStatus.RUNNING, ScanStatus.COMPLETED, ScanStatus.FAILED, ScanStatus.CANCELLED, ] for i, status in enumerate(statuses): scan = Scan(name=f"Scan {i}", target=f"target{i}.com", status=status) assert scan.status == status def test_scan_all_types_init(self): """Test Scan initialization with all possible scan types.""" types = [ ScanType.PORT_SCAN, ScanType.VULNERABILITY, ScanType.WEB_APP, ScanType.NETWORK, ScanType.COMPLIANCE, ScanType.FULL, ] for i, scan_type in enumerate(types): scan = Scan( name=f"Scan {i}", target=f"target{i}.com", scan_type=scan_type, ) assert scan.scan_type == scan_type def test_scan_config_default_empty_dict(self): """Test that config defaults to empty dict, not None.""" scan = Scan(name="Test", target="example.com") assert scan.config == {} assert isinstance(scan.config, dict) def test_scan_config_none_becomes_empty(self): """Test that passing None for config results in empty dict.""" scan = Scan(name="Test", target="example.com", config=None) assert scan.config == {} def test_scan_nested_config(self): """Test Scan with nested configuration.""" config = { "ports": [80, 443, 8080], "timeout": 30, "nmap": { "timing_template": "T4", "scripts": "default,vuln", }, "threads": 10, } scan = Scan(name="Test", target="example.com", config=config) assert scan.config["nmap"]["timing_template"] == "T4" assert scan.config["ports"] == [80, 443, 8080] def test_scan_target_variations(self): """Test Scan with various target formats.""" targets = [ "example.com", "192.168.1.1", "10.0.0.0/24", "https://example.com/path", "subdomain.example.co.uk", ] for i, target in enumerate(targets): scan = Scan(name=f"Scan {i}", target=target) assert scan.target == target def test_scan_name_variations(self): """Test Scan with various name formats.""" names = [ "Simple Scan", "Scan-with-dashes", "Scan_123", "Scan with numbers 123", "A" * 100, # Long name ] for name in names: scan = Scan(name=name, target="example.com") assert scan.name == name # ============================================================================ # Test Scan Class - Class Methods (find_one, find_many) # ============================================================================ @pytest.mark.asyncio class TestScanClassMethods: """Test Scan class methods.""" async def test_find_one_returns_none(self): """Test find_one returns None (stub implementation).""" result = await Scan.find_one(id="scan-123") assert result is None async def test_find_one_with_various_kwargs(self): """Test find_one with various keyword arguments.""" # Test with different filter parameters result = await Scan.find_one(name="Test Scan") assert result is None result = await Scan.find_one(target="example.com") assert result is None result = await Scan.find_one(status=ScanStatus.PENDING) assert result is None result = await Scan.find_one(name="Test", target="example.com", status=ScanStatus.RUNNING) assert result is None async def test_find_many_returns_empty_list(self): """Test find_many returns empty list (stub implementation).""" result = await Scan.find_many() assert result == [] assert isinstance(result, list) async def test_find_many_with_various_kwargs(self): """Test find_many with various keyword arguments.""" # Test with different filter parameters result = await Scan.find_many(status=ScanStatus.PENDING) assert result == [] result = await Scan.find_many(scan_type=ScanType.WEB_APP) assert result == [] result = await Scan.find_many(status=ScanStatus.COMPLETED, created_by="user-123") assert result == [] async def test_find_many_with_limit(self): """Test find_many with limit parameter.""" result = await Scan.find_many(limit=10) assert result == [] result = await Scan.find_many(limit=100, offset=0) assert result == [] # ============================================================================ # Test Scan Class - Instance Methods (save, update, to_response) # ============================================================================ @pytest.mark.asyncio class TestScanInstanceMethods: """Test Scan instance methods.""" async def test_save_does_nothing(self): """Test save method is a stub that doesn't raise.""" scan = Scan(name="Test", target="example.com") result = await scan.save() assert result is None # Stub returns nothing async def test_save_preserves_state(self): """Test save doesn't modify scan state.""" scan = Scan( name="Test Scan", target="example.com", status=ScanStatus.RUNNING, ) scan.progress = 50 await scan.save() assert scan.name == "Test Scan" assert scan.progress == 50 assert scan.status == ScanStatus.RUNNING async def test_update_single_field(self): """Test update with single field.""" scan = Scan(name="Test", target="example.com") await scan.update(status=ScanStatus.RUNNING) assert scan.status == ScanStatus.RUNNING async def test_update_multiple_fields(self): """Test update with multiple fields.""" scan = Scan(name="Test", target="example.com") await scan.update( status=ScanStatus.COMPLETED, progress=100, findings_count=5, error_message=None, ) assert scan.status == ScanStatus.COMPLETED assert scan.progress == 100 assert scan.findings_count == 5 assert scan.error_message is None async def test_update_all_statuses(self): """Test update with all status transitions.""" scan = Scan(name="Test", target="example.com") statuses = [ ScanStatus.PENDING, ScanStatus.RUNNING, ScanStatus.COMPLETED, ScanStatus.FAILED, ScanStatus.CANCELLED, ] for status in statuses: await scan.update(status=status) assert scan.status == status async def test_update_progress(self): """Test updating progress field.""" scan = Scan(name="Test", target="example.com") for progress in [0, 25, 50, 75, 100]: await scan.update(progress=progress) assert scan.progress == progress async def test_update_findings_count(self): """Test updating findings count.""" scan = Scan(name="Test", target="example.com") await scan.update(findings_count=10) assert scan.findings_count == 10 async def test_update_error_message(self): """Test updating error message.""" scan = Scan(name="Test", target="example.com") error_msg = "Connection timeout after 30 seconds" await scan.update(error_message=error_msg) assert scan.error_message == error_msg # Clear error await scan.update(error_message=None) assert scan.error_message is None async def test_update_timestamps(self): """Test updating timestamp fields.""" scan = Scan(name="Test", target="example.com") started_at = datetime.now(timezone.utc) completed_at = datetime.now(timezone.utc) await scan.update(started_at=started_at, completed_at=completed_at) assert scan.started_at == started_at assert scan.completed_at == completed_at async def test_update_config(self): """Test updating config field.""" scan = Scan(name="Test", target="example.com") new_config = {"ports": [22, 80, 443], "timeout": 60} await scan.update(config=new_config) assert scan.config == new_config async def test_update_schedule(self): """Test updating schedule field.""" scan = Scan(name="Test", target="example.com") schedule = {"enabled": True, "cron": "0 2 * * *"} await scan.update(schedule=schedule) assert scan.schedule == schedule async def test_update_custom_field(self): """Test update with custom field not in default schema.""" scan = Scan(name="Test", target="example.com") await scan.update(custom_field="custom_value") assert scan.custom_field == "custom_value" def test_to_response_basic(self): """Test to_response with basic scan.""" scan = Scan(name="Test Scan", target="example.com") response = scan.to_response() assert isinstance(response, dict) assert response["id"] == "scan-stub-id" assert response["name"] == "Test Scan" assert response["target"] == "example.com" assert response["scan_type"] == "port_scan" assert response["status"] == "pending" assert response["created_by"] is None assert response["config"] == {} assert response["schedule"] is None assert response["progress"] == 0 assert response["findings_count"] == 0 assert response["error_message"] is None assert response["started_at"] is None assert response["completed_at"] is None assert "created_at" in response def test_to_response_full_scan(self): """Test to_response with fully populated scan.""" created_at = datetime.now(timezone.utc) started_at = datetime.now(timezone.utc) completed_at = datetime.now(timezone.utc) scan = Scan( name="Full Scan", target="192.168.1.0/24", scan_type=ScanType.FULL, status=ScanStatus.COMPLETED, created_by="admin-user", config={"ports": "all", "aggressive": True}, schedule={"enabled": False}, ) scan.progress = 100 scan.findings_count = 25 scan.created_at = created_at scan.started_at = started_at scan.completed_at = completed_at response = scan.to_response() assert response["name"] == "Full Scan" assert response["target"] == "192.168.1.0/24" assert response["scan_type"] == "full" assert response["status"] == "completed" assert response["created_by"] == "admin-user" assert response["config"] == {"ports": "all", "aggressive": True} assert response["schedule"] == {"enabled": False} assert response["progress"] == 100 assert response["findings_count"] == 25 assert response["started_at"] == started_at.isoformat() assert response["completed_at"] == completed_at.isoformat() assert response["created_at"] == created_at.isoformat() def test_to_response_all_scan_types(self): """Test to_response with all scan types.""" type_values = { ScanType.PORT_SCAN: "port_scan", ScanType.VULNERABILITY: "vulnerability", ScanType.WEB_APP: "web_app", ScanType.NETWORK: "network", ScanType.COMPLIANCE: "compliance", ScanType.FULL: "full", } for scan_type, expected_value in type_values.items(): scan = Scan(name="Test", target="example.com", scan_type=scan_type) response = scan.to_response() assert response["scan_type"] == expected_value def test_to_response_all_statuses(self): """Test to_response with all scan statuses.""" status_values = { ScanStatus.PENDING: "pending", ScanStatus.RUNNING: "running", ScanStatus.COMPLETED: "completed", ScanStatus.FAILED: "failed", ScanStatus.CANCELLED: "cancelled", } for status, expected_value in status_values.items(): scan = Scan(name="Test", target="example.com", status=status) response = scan.to_response() assert response["status"] == expected_value def test_to_response_datetime_serialization(self): """Test that datetime objects are properly serialized.""" created_at = datetime(2024, 1, 15, 10, 30, 0) started_at = datetime(2024, 1, 15, 10, 31, 0) completed_at = datetime(2024, 1, 15, 10, 35, 0) scan = Scan(name="Test", target="example.com") scan.created_at = created_at scan.started_at = started_at scan.completed_at = completed_at response = scan.to_response() assert response["created_at"] == "2024-01-15T10:30:00" assert response["started_at"] == "2024-01-15T10:31:00" assert response["completed_at"] == "2024-01-15T10:35:00" def test_to_response_with_error(self): """Test to_response when scan has error.""" scan = Scan( name="Failed Scan", target="example.com", status=ScanStatus.FAILED, ) scan.error_message = "Network unreachable" response = scan.to_response() assert response["status"] == "failed" assert response["error_message"] == "Network unreachable" # ============================================================================ # Test Scan Class - State Transitions # ============================================================================ @pytest.mark.asyncio class TestScanStateTransitions: """Test scan state transitions.""" async def test_pending_to_running(self): """Test transition from pending to running.""" scan = Scan(name="Test", target="example.com") assert scan.status == ScanStatus.PENDING await scan.update(status=ScanStatus.RUNNING) assert scan.status == ScanStatus.RUNNING async def test_running_to_completed(self): """Test transition from running to completed.""" scan = Scan(name="Test", target="example.com", status=ScanStatus.RUNNING) await scan.update(status=ScanStatus.COMPLETED, progress=100, findings_count=10) assert scan.status == ScanStatus.COMPLETED assert scan.progress == 100 async def test_running_to_failed(self): """Test transition from running to failed.""" scan = Scan(name="Test", target="example.com", status=ScanStatus.RUNNING) await scan.update(status=ScanStatus.FAILED, error_message="Timeout error") assert scan.status == ScanStatus.FAILED assert scan.error_message == "Timeout error" async def test_pending_to_cancelled(self): """Test transition from pending to cancelled.""" scan = Scan(name="Test", target="example.com") await scan.update(status=ScanStatus.CANCELLED) assert scan.status == ScanStatus.CANCELLED async def test_running_to_cancelled(self): """Test transition from running to cancelled.""" scan = Scan(name="Test", target="example.com", status=ScanStatus.RUNNING) await scan.update(status=ScanStatus.CANCELLED) assert scan.status == ScanStatus.CANCELLED async def test_progress_updates_during_run(self): """Test progress updates during scan execution.""" scan = Scan(name="Test", target="example.com", status=ScanStatus.RUNNING) progress_values = [10, 25, 50, 75, 90, 100] for progress in progress_values: await scan.update(progress=progress) assert scan.progress == progress async def test_findings_increment_during_scan(self): """Test findings count increment during scan.""" scan = Scan(name="Test", target="example.com", status=ScanStatus.RUNNING) # Simulate findings being added for i in range(1, 6): await scan.update(findings_count=i) assert scan.findings_count == i # ============================================================================ # Test Scan Class - Integration Scenarios # ============================================================================ @pytest.mark.asyncio class TestScanIntegrationScenarios: """Test realistic scan workflow scenarios.""" async def test_complete_scan_workflow(self): """Test a complete scan workflow from creation to completion.""" # Create scan scan = Scan( name="Full Security Assessment", target="target.example.com", scan_type=ScanType.FULL, created_by="security-analyst-001", config={ "ports": [80, 443, 8080, 22], "threads": 20, "timeout": 300, }, ) # Initial state assert scan.status == ScanStatus.PENDING assert scan.progress == 0 assert scan.findings_count == 0 # Start scan await scan.update(status=ScanStatus.RUNNING, started_at=datetime.now(timezone.utc)) assert scan.status == ScanStatus.RUNNING # Update progress await scan.update(progress=25) assert scan.progress == 25 # Find some vulnerabilities await scan.update(findings_count=3) assert scan.findings_count == 3 # More progress await scan.update(progress=75, findings_count=8) assert scan.progress == 75 assert scan.findings_count == 8 # Complete scan await scan.update( status=ScanStatus.COMPLETED, progress=100, findings_count=12, completed_at=datetime.now(timezone.utc), ) assert scan.status == ScanStatus.COMPLETED assert scan.progress == 100 assert scan.findings_count == 12 # Verify response format response = scan.to_response() assert response["status"] == "completed" assert response["progress"] == 100 assert response["findings_count"] == 12 async def test_scan_failure_workflow(self): """Test a scan that fails during execution.""" scan = Scan( name="Network Scan", target="10.0.0.0/24", scan_type=ScanType.NETWORK, status=ScanStatus.RUNNING, ) scan.started_at = datetime.now(timezone.utc) # Progress partially await scan.update(progress=50, findings_count=5) assert scan.progress == 50 # Error occurs await scan.update( status=ScanStatus.FAILED, error_message="Network connection lost at 50%", completed_at=datetime.now(timezone.utc), ) assert scan.status == ScanStatus.FAILED assert "connection lost" in scan.error_message response = scan.to_response() assert response["status"] == "failed" assert "error_message" in response async def test_scan_cancellation_workflow(self): """Test a scan that gets cancelled.""" scan = Scan( name="Compliance Scan", target="internal-app.company.com", scan_type=ScanType.COMPLIANCE, status=ScanStatus.RUNNING, ) scan.started_at = datetime.now(timezone.utc) scan.progress = 30 # User cancels await scan.update( status=ScanStatus.CANCELLED, completed_at=datetime.now(timezone.utc), ) assert scan.status == ScanStatus.CANCELLED response = scan.to_response() assert response["status"] == "cancelled" async def test_multiple_scans_find_many(self): """Test creating multiple scans and using find_many.""" scans = [] for i in range(5): scan = Scan( name=f"Scan {i}", target=f"target{i}.example.com", scan_type=ScanType.VULNERABILITY, status=ScanStatus.PENDING, ) scans.append(scan) # find_many should return empty list (stub) result = await Scan.find_many(status=ScanStatus.PENDING) assert result == [] async def test_scheduled_scan(self): """Test a scheduled scan configuration.""" schedule = { "enabled": True, "cron": "0 2 * * 0", # Weekly on Sunday at 2 AM "timezone": "America/New_York", } scan = Scan( name="Weekly Security Scan", target="production.example.com", scan_type=ScanType.FULL, schedule=schedule, ) assert scan.schedule == schedule response = scan.to_response() assert response["schedule"] == schedule # ============================================================================ # Test Scan Class - Edge Cases and Error Handling # ============================================================================ class TestScanEdgeCases: """Test edge cases and error handling.""" def test_scan_with_empty_strings(self): """Test Scan with empty string values.""" scan = Scan(name="", target="") assert scan.name == "" assert scan.target == "" def test_scan_with_unicode(self): """Test Scan with unicode characters.""" scan = Scan( name="スキャン テスト", # Japanese target="测试.example.com", # Chinese ) assert scan.name == "スキャン テスト" assert scan.target == "测试.example.com" def test_scan_with_special_characters(self): """Test Scan with special characters in name.""" name = "Test Scan [2024] - (Production) @ 10:00" scan = Scan(name=name, target="example.com") assert scan.name == name def test_scan_config_with_various_types(self): """Test config with various data types.""" config = { "string": "value", "integer": 42, "float": 3.14, "boolean": True, "null": None, "list": [1, 2, 3], "nested": {"key": "value"}, } scan = Scan(name="Test", target="example.com", config=config) assert scan.config == config def test_scan_id_is_string(self): """Test that scan id is always a string.""" scan = Scan(name="Test", target="example.com") assert isinstance(scan.id, str) assert scan.id == "scan-stub-id" def test_scan_created_at_is_datetime(self): """Test that created_at is a datetime object.""" scan = Scan(name="Test", target="example.com") assert isinstance(scan.created_at, datetime) def test_to_response_id_is_string(self): """Test that to_response id is a string.""" scan = Scan(name="Test", target="example.com") response = scan.to_response() assert isinstance(response["id"], str) def test_update_preserves_unmodified_fields(self): """Test that update only modifies specified fields.""" scan = Scan( name="Test Scan", target="example.com", status=ScanStatus.PENDING, ) scan.progress = 0 scan.findings_count = 0 # Update only status import asyncio asyncio.run(scan.update(status=ScanStatus.RUNNING)) # Other fields should be preserved assert scan.name == "Test Scan" assert scan.target == "example.com" assert scan.progress == 0 assert scan.findings_count == 0 assert scan.status == ScanStatus.RUNNING # ============================================================================ # Test Scan Class - Serialization Consistency # ============================================================================ class TestScanSerialization: """Test serialization consistency and format.""" def test_to_response_returns_dict(self): """Test to_response always returns a dictionary.""" scan = Scan(name="Test", target="example.com") response = scan.to_response() assert isinstance(response, dict) def test_to_response_has_required_keys(self): """Test to_response has all required keys.""" scan = Scan(name="Test", target="example.com") response = scan.to_response() required_keys = [ "id", "name", "target", "scan_type", "status", "created_by", "config", "schedule", "created_at", "started_at", "completed_at", "progress", "findings_count", "error_message", ] for key in required_keys: assert key in response, f"Missing required key: {key}" def test_to_response_consistency(self): """Test that to_response is consistent across multiple calls.""" scan = Scan(name="Test", target="example.com") response1 = scan.to_response() response2 = scan.to_response() assert response1 == response2 def test_to_response_after_update(self): """Test to_response reflects updates.""" scan = Scan(name="Test", target="example.com") initial_response = scan.to_response() assert initial_response["status"] == "pending" import asyncio asyncio.run(scan.update(status=ScanStatus.RUNNING, progress=50)) updated_response = scan.to_response() assert updated_response["status"] == "running" assert updated_response["progress"] == 50 # ============================================================================ # Test Scan Class - Async Method Behavior # ============================================================================ @pytest.mark.asyncio class TestScanAsyncBehavior: """Test async method behavior.""" async def test_save_is_awaitable(self): """Test that save can be awaited.""" scan = Scan(name="Test", target="example.com") # Should not raise await scan.save() async def test_update_is_awaitable(self): """Test that update can be awaited.""" scan = Scan(name="Test", target="example.com") # Should not raise await scan.update(status=ScanStatus.RUNNING) async def test_find_one_is_awaitable(self): """Test that find_one can be awaited.""" # Should not raise result = await Scan.find_one(id="test") assert result is None async def test_find_many_is_awaitable(self): """Test that find_many can be awaited.""" # Should not raise result = await Scan.find_many() assert result == [] async def test_multiple_concurrent_saves(self): """Test multiple concurrent save calls.""" scan = Scan(name="Test", target="example.com") # Multiple concurrent saves should not fail await asyncio.gather( scan.save(), scan.save(), scan.save(), ) async def test_multiple_concurrent_updates(self): """Test multiple concurrent update calls.""" scan = Scan(name="Test", target="example.com") # Multiple concurrent updates should apply all changes await asyncio.gather( scan.update(progress=10), scan.update(findings_count=5), scan.update(status=ScanStatus.RUNNING), ) assert scan.progress == 10 assert scan.findings_count == 5 assert scan.status == ScanStatus.RUNNING # Import asyncio for async tests import asyncio
"""
Comprehensive Tests for API Scan Model
=======================================
Target: 90-100% Coverage for /api/models/scan.py
Tests all scan states, configurations, and methods.
Coverage targets:
- ScanStatus enum: 100%
- ScanType enum: 100%
- Scan class: 90-100%
- __init__: all parameters
- find_one: classmethod
- find_many: classmethod
- save: async method
- update: async method
- to_response: serialization
"""
from datetime import datetime, timezone
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
# Import the module under test
from api.models.scan import Scan, ScanStatus, ScanType
# ============================================================================
# Test ScanStatus Enum
# ============================================================================
class TestScanStatusEnum:
"""Test ScanStatus enumeration values and behavior."""
def test_scan_status_values(self):
"""Test all ScanStatus enum values are correct."""
assert ScanStatus.PENDING.value == "pending"
assert ScanStatus.RUNNING.value == "running"
assert ScanStatus.COMPLETED.value == "completed"
assert ScanStatus.FAILED.value == "failed"
assert ScanStatus.CANCELLED.value == "cancelled"
def test_scan_status_enum_members(self):
"""Test ScanStatus enum members exist."""
assert hasattr(ScanStatus, "PENDING")
assert hasattr(ScanStatus, "RUNNING")
assert hasattr(ScanStatus, "COMPLETED")
assert hasattr(ScanStatus, "FAILED")
assert hasattr(ScanStatus, "CANCELLED")
def test_scan_status_comparison(self):
"""Test ScanStatus enum comparison."""
assert ScanStatus.PENDING == ScanStatus.PENDING
assert ScanStatus.RUNNING != ScanStatus.COMPLETED
def test_scan_status_from_string(self):
"""Test creating ScanStatus from string value."""
status = ScanStatus("pending")
assert status == ScanStatus.PENDING
status = ScanStatus("running")
assert status == ScanStatus.RUNNING
status = ScanStatus("completed")
assert status == ScanStatus.COMPLETED
status = ScanStatus("failed")
assert status == ScanStatus.FAILED
status = ScanStatus("cancelled")
assert status == ScanStatus.CANCELLED
def test_scan_status_invalid_value(self):
"""Test ScanStatus with invalid value raises error."""
with pytest.raises(ValueError):
ScanStatus("invalid_status")
# ============================================================================
# Test ScanType Enum
# ============================================================================
class TestScanTypeEnum:
"""Test ScanType enumeration values and behavior."""
def test_scan_type_values(self):
"""Test all ScanType enum values are correct."""
assert ScanType.PORT_SCAN.value == "port_scan"
assert ScanType.VULNERABILITY.value == "vulnerability"
assert ScanType.WEB_APP.value == "web_app"
assert ScanType.NETWORK.value == "network"
assert ScanType.COMPLIANCE.value == "compliance"
assert ScanType.FULL.value == "full"
def test_scan_type_enum_members(self):
"""Test ScanType enum members exist."""
assert hasattr(ScanType, "PORT_SCAN")
assert hasattr(ScanType, "VULNERABILITY")

Xet Storage Details

Size:
34.7 kB
·
Xet hash:
c90a647c897ad3e91cf07e61566d118443b9a54a009a459b672d7fe1f9452597

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.