Buckets:

download
raw
44.7 kB
""" Unit tests for core/models.py Tests all Pydantic models, validators, and properties """ from datetime import datetime, timedelta, timezone from typing import List, Optional import pytest from core.models import ( APIKeyConfig, BackendType, DomainRecon, Finding, HealthStatus, LLMRequest, LLMResponse, PaginatedResponse, ReportConfig, ScanConfig, ScanResult, ScanStatus, Severity, SubdomainInfo, TimestampedModel, ) # ============================================================================= # Enum Tests # ============================================================================= class TestSeverity: """Tests for Severity enum""" def test_severity_values(self): """Test all severity enum values exist""" assert Severity.CRITICAL == "critical" assert Severity.HIGH == "high" assert Severity.MEDIUM == "medium" assert Severity.LOW == "low" assert Severity.INFO == "info" def test_severity_is_str_enum(self): """Test Severity is a string enum""" assert isinstance(Severity.HIGH, str) assert issubclass(Severity, str) class TestScanStatus: """Tests for ScanStatus enum""" def test_scan_status_values(self): """Test all scan status enum values exist""" assert ScanStatus.PENDING == "pending" assert ScanStatus.RUNNING == "running" assert ScanStatus.COMPLETED == "completed" assert ScanStatus.FAILED == "failed" assert ScanStatus.CANCELLED == "cancelled" class TestBackendType: """Tests for BackendType enum""" def test_backend_type_values(self): """Test all backend type enum values exist""" assert BackendType.DUCKDUCKGO == "duckduckgo" assert BackendType.OPENROUTER == "openrouter" assert BackendType.OPENAI == "openai" assert BackendType.ANTHROPIC == "anthropic" # ============================================================================= # TimestampedModel Tests # ============================================================================= class TestTimestampedModel: """Tests for TimestampedModel base class""" def test_default_creation(self): """Test model creation with default timestamps""" before = datetime.now(timezone.utc) model = TimestampedModel() after = datetime.now(timezone.utc) # Note: Model uses utcnow() internally which creates naive datetime assert before <= model.created_at <= after assert model.updated_at is None def test_custom_timestamps(self): """Test model with custom timestamps""" created = datetime(2024, 1, 1, 12, 0, 0) updated = datetime(2024, 1, 2, 12, 0, 0) model = TimestampedModel(created_at=created, updated_at=updated) assert model.created_at == created assert model.updated_at == updated def test_from_attributes_config(self): """Test model_config allows from_attributes""" assert TimestampedModel.model_config.get("from_attributes") is True # ============================================================================= # APIKeyConfig Tests # ============================================================================= class TestAPIKeyConfig: """Tests for APIKeyConfig model""" def test_default_creation(self): """Test creating config with no keys""" config = APIKeyConfig() assert config.openrouter_key is None assert config.openai_key is None assert config.anthropic_key is None assert config.github_token is None assert config.shodan_key is None def test_valid_openrouter_key(self): """Test valid OpenRouter key format""" config = APIKeyConfig(openrouter_key="sk-or-test12345678901234567890") assert config.openrouter_key == "sk-or-test12345678901234567890" def test_invalid_openrouter_key_pattern(self): """Test invalid OpenRouter key raises error""" with pytest.raises(ValueError): APIKeyConfig(openrouter_key="invalid-key") def test_valid_openai_key(self): """Test valid OpenAI key format""" config = APIKeyConfig(openai_key="sk-test12345678901234567890") assert config.openai_key == "sk-test12345678901234567890" def test_invalid_openai_key_pattern(self): """Test invalid OpenAI key raises error""" with pytest.raises(ValueError): APIKeyConfig(openai_key="invalid") def test_valid_anthropic_key(self): """Test valid Anthropic key format""" config = APIKeyConfig(anthropic_key="sk-ant-test12345678901234567890") assert config.anthropic_key == "sk-ant-test12345678901234567890" def test_invalid_anthropic_key_pattern(self): """Test invalid Anthropic key raises error""" with pytest.raises(ValueError): APIKeyConfig(anthropic_key="invalid-key") def test_github_token_min_length(self): """Test GitHub token minimum length validation""" with pytest.raises(ValueError): APIKeyConfig(github_token="short") def test_valid_github_token(self): """Test valid GitHub token""" config = APIKeyConfig(github_token="ghp_12345678901234567890") assert config.github_token == "ghp_12345678901234567890" def test_shodan_key_no_validation(self): """Test Shodan key has no pattern validation""" config = APIKeyConfig(shodan_key="any-value-works") assert config.shodan_key == "any-value-works" def test_get_key_openrouter(self): """Test get_key returns correct key for OPENROUTER""" config = APIKeyConfig(openrouter_key="sk-or-test12345678901234567890") assert config.get_key(BackendType.OPENROUTER) == "sk-or-test12345678901234567890" def test_get_key_openai(self): """Test get_key returns correct key for OPENAI""" config = APIKeyConfig(openai_key="sk-test12345678901234567890") assert config.get_key(BackendType.OPENAI) == "sk-test12345678901234567890" def test_get_key_anthropic(self): """Test get_key returns correct key for ANTHROPIC""" config = APIKeyConfig(anthropic_key="sk-ant-test12345678901234567890") assert config.get_key(BackendType.ANTHROPIC) == "sk-ant-test12345678901234567890" def test_get_key_duckduckgo(self): """Test get_key returns None for DUCKDUCKGO (no API key needed)""" config = APIKeyConfig() assert config.get_key(BackendType.DUCKDUCKGO) is None def test_get_key_missing(self): """Test get_key returns None when key not set""" config = APIKeyConfig() assert config.get_key(BackendType.OPENAI) is None def test_extra_forbidden(self): """Test extra fields are forbidden""" with pytest.raises(ValueError): APIKeyConfig(invalid_field="test") def test_mask_keys_validator_with_value(self): """Test mask_keys validator passes through value (masking happens in repr)""" long_token = "ghp_12345678901234567890" config = APIKeyConfig(github_token=long_token) # Values pass through validator unchanged (masking happens in repr) assert config.github_token == long_token def test_mask_keys_validator_with_none(self): """Test mask_keys validator with None value""" # When value is None, it should pass through unchanged config = APIKeyConfig(openrouter_key=None) assert config.openrouter_key is None def test_mask_keys_validator_with_short_value(self): """Test mask_keys validator with short value (less than 10 chars)""" # Note: github_token has min_length=20, so we test with shodan_key which has no pattern config = APIKeyConfig(shodan_key="short") # Short values pass through assert config.shodan_key == "short" # ============================================================================= # ScanConfig Tests # ============================================================================= class TestScanConfig: """Tests for ScanConfig model""" def test_default_creation(self): """Test default scan configuration""" config = ScanConfig(target="example.com") assert config.target == "example.com" assert config.scan_type == "quick" assert config.ports == [80, 443] assert config.templates == [] assert config.timeout == 300 assert config.concurrent == 5 assert config.follow_redirects is True def test_valid_target_domain(self): """Test valid domain target""" config = ScanConfig(target="example.com") assert config.target == "example.com" def test_valid_target_subdomain(self): """Test valid subdomain target""" config = ScanConfig(target="sub.example.com") assert config.target == "sub.example.com" def test_valid_target_ip(self): """Test valid IP target""" config = ScanConfig(target="192.168.1.1") assert config.target == "192.168.1.1" def test_target_lowercasing(self): """Test target is lowercased""" config = ScanConfig(target="EXAMPLE.COM") assert config.target == "example.com" def test_target_stripping(self): """Test target is stripped of whitespace""" config = ScanConfig(target=" example.com ") assert config.target == "example.com" def test_invalid_target_dangerous_chars(self): """Test target with dangerous characters raises error""" dangerous_chars = [ ";", "&", "|", "`", "$", "(", ")", "{", "}", "[", "]", "\\", "'", '"', "<", ">", ] for char in dangerous_chars: with pytest.raises(ValueError): ScanConfig(target=f"example{char}com") def test_invalid_target_format(self): """Test invalid target format raises error""" with pytest.raises(ValueError): ScanConfig(target="not-a-valid-target!!!") def test_target_domain_starting_with_hyphen(self): """Test domain starting with hyphen raises error (neither domain nor IP)""" # Tests branch where domain pattern doesn't match AND IP pattern doesn't match # Domain regex requires [a-z0-9] at start, hyphen is not allowed # IP regex doesn't match because it's not in IP format with pytest.raises(ValueError) as exc_info: ScanConfig(target="-example.com") assert "Invalid target format" in str(exc_info.value) def test_target_ending_with_hyphen(self): """Test domain ending with hyphen raises error""" # Domain regex requires [a-z0-9] at end with pytest.raises(ValueError): ScanConfig(target="example.com-") # ends with hyphen, not dot def test_target_with_space(self): """Test domain with space raises error""" with pytest.raises(ValueError): ScanConfig(target="exam ple.com") def test_target_with_underscore(self): """Test domain with underscore raises error""" with pytest.raises(ValueError): ScanConfig(target="exam_ple.com") def test_empty_target_raises_error(self): """Test empty target raises error""" with pytest.raises(ValueError): ScanConfig(target="") def test_target_too_long(self): """Test target exceeding max length raises error""" with pytest.raises(ValueError): ScanConfig(target="a" * 254) def test_valid_scan_types(self): """Test all valid scan types""" for scan_type in ["quick", "full", "stealth"]: config = ScanConfig(target="example.com", scan_type=scan_type) assert config.scan_type == scan_type def test_invalid_scan_type(self): """Test invalid scan type raises error""" with pytest.raises(ValueError): ScanConfig(target="example.com", scan_type="invalid") def test_valid_ports(self): """Test valid port numbers""" config = ScanConfig(target="example.com", ports=[80, 443, 8080, 65535]) assert config.ports == [80, 443, 8080, 65535] def test_invalid_port_too_low(self): """Test port below 1 raises error""" with pytest.raises(ValueError): ScanConfig(target="example.com", ports=[0]) def test_invalid_port_too_high(self): """Test port above 65535 raises error""" with pytest.raises(ValueError): ScanConfig(target="example.com", ports=[65536]) def test_timeout_bounds(self): """Test timeout validation bounds""" # Minimum with pytest.raises(ValueError): ScanConfig(target="example.com", timeout=9) # Maximum with pytest.raises(ValueError): ScanConfig(target="example.com", timeout=3601) # Valid config = ScanConfig(target="example.com", timeout=100) assert config.timeout == 100 def test_concurrent_bounds(self): """Test concurrent validation bounds""" # Minimum with pytest.raises(ValueError): ScanConfig(target="example.com", concurrent=0) # Maximum with pytest.raises(ValueError): ScanConfig(target="example.com", concurrent=51) # Valid config = ScanConfig(target="example.com", concurrent=10) assert config.concurrent == 10 def test_extra_forbidden(self): """Test extra fields are forbidden""" with pytest.raises(ValueError): ScanConfig(target="example.com", invalid_field="test") # ============================================================================= # Finding Tests # ============================================================================= class TestFinding: """Tests for Finding model""" def test_minimal_creation(self): """Test minimal finding creation""" finding = Finding( title="Test Finding", description="Test description", severity=Severity.HIGH, host="example.com", ) assert finding.title == "Test Finding" assert finding.description == "Test description" assert finding.severity == Severity.HIGH assert finding.host == "example.com" assert finding.id is None assert finding.port is None assert finding.cvss_score is None def test_full_creation(self): """Test finding with all fields""" finding = Finding( id="find-001", title="SQL Injection", description="SQL injection vulnerability found", severity=Severity.CRITICAL, cvss_score=9.8, host="example.com", port=443, service="HTTPS", evidence="Error message: SQL syntax error", remediation="Use parameterized queries", references=["https://owasp.org/sql-injection"], cve_ids=["CVE-2023-1234"], tags=["sql", "injection", "web"], confidence="confirmed", ) assert finding.id == "find-001" assert finding.cvss_score == 9.8 assert finding.port == 443 assert finding.confidence == "confirmed" def test_default_confidence(self): """Test default confidence is 'possible'""" finding = Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", ) assert finding.confidence == "possible" def test_cvss_score_bounds(self): """Test CVSS score validation""" # Below minimum with pytest.raises(ValueError): Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", cvss_score=-0.1, ) # Above maximum with pytest.raises(ValueError): Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", cvss_score=10.1, ) # Valid finding = Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", cvss_score=5.5, ) assert finding.cvss_score == 5.5 def test_port_bounds(self): """Test port validation""" with pytest.raises(ValueError): Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", port=0, ) with pytest.raises(ValueError): Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", port=70000, ) def test_valid_cve_format(self): """Test valid CVE ID format""" finding = Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", cve_ids=["CVE-2023-1234", "CVE-2024-56789"], ) # CVEs should be uppercased assert finding.cve_ids == ["CVE-2023-1234", "CVE-2024-56789"] def test_invalid_cve_format(self): """Test invalid CVE ID format raises error""" with pytest.raises(ValueError): Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", cve_ids=["invalid-cve"], ) def test_cve_lowercase_input(self): """Test lowercase CVE input is converted to uppercase""" finding = Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", cve_ids=["cve-2023-1234"], ) assert finding.cve_ids == ["CVE-2023-1234"] def test_empty_title_raises_error(self): """Test empty title raises error""" with pytest.raises(ValueError): Finding( title="", description="Test", severity=Severity.LOW, host="example.com", ) def test_title_too_long(self): """Test title exceeding max length raises error""" with pytest.raises(ValueError): Finding( title="A" * 501, description="Test", severity=Severity.LOW, host="example.com", ) def test_empty_description_raises_error(self): """Test empty description raises error""" with pytest.raises(ValueError): Finding( title="Test", description="", severity=Severity.LOW, host="example.com", ) # ============================================================================= # ScanResult Tests # ============================================================================= class TestScanResult: """Tests for ScanResult model""" def test_minimal_creation(self): """Test minimal scan result creation""" started = datetime.now(timezone.utc) result = ScanResult( scan_id="scan-001", target="example.com", status=ScanStatus.COMPLETED, started_at=started, ) assert result.scan_id == "scan-001" assert result.target == "example.com" assert result.status == ScanStatus.COMPLETED assert result.started_at == started assert result.findings == [] assert result.stats == {} assert result.error_message is None assert result.completed_at is None def test_with_findings(self): """Test scan result with findings""" finding = Finding( title="Test", description="Test", severity=Severity.HIGH, host="example.com", ) result = ScanResult( scan_id="scan-001", target="example.com", status=ScanStatus.COMPLETED, started_at=datetime.now(timezone.utc), findings=[finding], ) assert len(result.findings) == 1 assert result.findings[0].title == "Test" def test_duration_seconds_completed(self): """Test duration calculation for completed scan""" started = datetime.now(timezone.utc) completed = started + timedelta(minutes=5) result = ScanResult( scan_id="scan-001", target="example.com", status=ScanStatus.COMPLETED, started_at=started, completed_at=completed, ) assert result.duration_seconds == 300.0 def test_duration_seconds_running(self): """Test duration is None for running scan""" result = ScanResult( scan_id="scan-001", target="example.com", status=ScanStatus.RUNNING, started_at=datetime.now(timezone.utc), ) assert result.duration_seconds is None def test_severity_counts(self): """Test severity_counts property""" findings = [ Finding( title="Critical", description="Test", severity=Severity.CRITICAL, host="example.com", ), Finding( title="High 1", description="Test", severity=Severity.HIGH, host="example.com", ), Finding( title="High 2", description="Test", severity=Severity.HIGH, host="example.com", ), Finding( title="Medium", description="Test", severity=Severity.MEDIUM, host="example.com", ), ] result = ScanResult( scan_id="scan-001", target="example.com", status=ScanStatus.COMPLETED, started_at=datetime.now(timezone.utc), findings=findings, ) counts = result.severity_counts assert counts["critical"] == 1 assert counts["high"] == 2 assert counts["medium"] == 1 assert counts["low"] == 0 assert counts["info"] == 0 def test_severity_counts_empty(self): """Test severity_counts with no findings""" result = ScanResult( scan_id="scan-001", target="example.com", status=ScanStatus.COMPLETED, started_at=datetime.now(timezone.utc), findings=[], ) counts = result.severity_counts assert all(count == 0 for count in counts.values()) # ============================================================================= # LLMRequest Tests # ============================================================================= class TestLLMRequest: """Tests for LLMRequest model""" def test_default_creation(self): """Test default LLM request creation""" request = LLMRequest(prompt="Hello") assert request.prompt == "Hello" assert request.system_prompt is None assert request.temperature == 0.7 assert request.max_tokens is None assert request.backend is None def test_full_creation(self): """Test LLM request with all fields""" request = LLMRequest( prompt="Hello world", system_prompt="You are a helpful assistant", temperature=0.5, max_tokens=1000, backend=BackendType.OPENAI, ) assert request.prompt == "Hello world" assert request.system_prompt == "You are a helpful assistant" assert request.temperature == 0.5 assert request.max_tokens == 1000 assert request.backend == BackendType.OPENAI def test_empty_prompt_raises_error(self): """Test empty prompt raises error""" with pytest.raises(ValueError): LLMRequest(prompt="") def test_prompt_too_long(self): """Test prompt exceeding max length raises error""" with pytest.raises(ValueError): LLMRequest(prompt="A" * 10001) def test_system_prompt_too_long(self): """Test system prompt exceeding max length raises error""" with pytest.raises(ValueError): LLMRequest(prompt="Hello", system_prompt="A" * 5001) def test_temperature_bounds(self): """Test temperature validation""" # Below minimum with pytest.raises(ValueError): LLMRequest(prompt="Hello", temperature=-0.1) # Above maximum with pytest.raises(ValueError): LLMRequest(prompt="Hello", temperature=2.1) # Valid at boundaries request1 = LLMRequest(prompt="Hello", temperature=0.0) assert request1.temperature == 0.0 request2 = LLMRequest(prompt="Hello", temperature=2.0) assert request2.temperature == 2.0 def test_max_tokens_bounds(self): """Test max_tokens validation""" with pytest.raises(ValueError): LLMRequest(prompt="Hello", max_tokens=0) with pytest.raises(ValueError): LLMRequest(prompt="Hello", max_tokens=32001) def test_sanitize_prompt_removes_null_bytes(self): """Test prompt sanitization removes null bytes""" request = LLMRequest(prompt="Hello\x00World") assert "\x00" not in request.prompt def test_sanitize_prompt_removes_control_chars(self): """Test prompt sanitization removes control characters""" request = LLMRequest(prompt="Hello\x01\x02\x03World") assert request.prompt == "HelloWorld" def test_sanitize_prompt_keeps_newlines_and_tabs(self): """Test prompt sanitization keeps newlines and tabs""" request = LLMRequest(prompt="Hello\n\tWorld") assert request.prompt == "Hello\n\tWorld" def test_sanitize_prompt_strips_whitespace(self): """Test prompt sanitization strips whitespace""" request = LLMRequest(prompt=" Hello World ") assert request.prompt == "Hello World" def test_extra_forbidden(self): """Test extra fields are forbidden""" with pytest.raises(ValueError): LLMRequest(prompt="Hello", invalid_field="test") # ============================================================================= # LLMResponse Tests # ============================================================================= class TestLLMResponse: """Tests for LLMResponse model""" def test_minimal_creation(self): """Test minimal LLM response creation""" response = LLMResponse(content="Hello", backend=BackendType.OPENAI) assert response.content == "Hello" assert response.backend == BackendType.OPENAI assert response.model is None assert response.tokens_used is None assert response.latency_ms is None assert response.cached is False assert response.error is None def test_full_creation(self): """Test LLM response with all fields""" response = LLMResponse( content="Hello world", backend=BackendType.ANTHROPIC, model="claude-3", tokens_used=150, latency_ms=500.5, cached=True, error=None, ) assert response.model == "claude-3" assert response.tokens_used == 150 assert response.latency_ms == 500.5 assert response.cached is True def test_success_property_true(self): """Test success property returns True when no error""" response = LLMResponse(content="Hello", backend=BackendType.OPENAI) assert response.success is True def test_success_property_false(self): """Test success property returns False when error present""" response = LLMResponse(content="", backend=BackendType.OPENAI, error="Rate limit exceeded") assert response.success is False # ============================================================================= # SubdomainInfo Tests # ============================================================================= class TestSubdomainInfo: """Tests for SubdomainInfo model""" def test_minimal_creation(self): """Test minimal subdomain info creation""" info = SubdomainInfo(name="sub.example.com") assert info.name == "sub.example.com" assert info.ip_addresses == [] assert info.technologies == [] assert info.ports == [] assert info.is_alive is False def test_full_creation(self): """Test subdomain info with all fields""" info = SubdomainInfo( name="api.example.com", ip_addresses=["192.168.1.1", "10.0.0.1"], technologies=["nginx", "PHP"], ports=[80, 443, 8080], is_alive=True, ) assert info.name == "api.example.com" assert info.ip_addresses == ["192.168.1.1", "10.0.0.1"] assert info.technologies == ["nginx", "PHP"] assert info.ports == [80, 443, 8080] assert info.is_alive is True # ============================================================================= # DomainRecon Tests # ============================================================================= class TestDomainRecon: """Tests for DomainRecon model""" def test_minimal_creation(self): """Test minimal domain recon creation""" recon = DomainRecon(domain="example.com") assert recon.domain == "example.com" assert recon.registrar is None assert recon.creation_date is None assert recon.expiration_date is None assert recon.name_servers == [] assert recon.subdomains == [] assert recon.emails == [] assert recon.technologies == [] def test_full_creation(self): """Test domain recon with all fields""" subdomain = SubdomainInfo(name="api.example.com", is_alive=True) recon = DomainRecon( domain="example.com", registrar="GoDaddy", creation_date=datetime(2020, 1, 1), expiration_date=datetime(2025, 1, 1), name_servers=["ns1.example.com", "ns2.example.com"], subdomains=[subdomain], emails=["admin@example.com"], technologies=["WordPress", "Apache"], ) assert recon.registrar == "GoDaddy" assert recon.creation_date == datetime(2020, 1, 1) assert len(recon.subdomains) == 1 assert recon.subdomains[0].name == "api.example.com" # ============================================================================= # HealthStatus Tests # ============================================================================= class TestHealthStatus: """Tests for HealthStatus model""" def test_creation(self): """Test health status creation""" status = HealthStatus( status="healthy", version="1.0.0", uptime_seconds=3600.5, checks={"database": True, "redis": True}, backends={"openai": "connected", "anthropic": "degraded"}, ) assert status.status == "healthy" assert status.version == "1.0.0" assert status.uptime_seconds == 3600.5 assert status.checks == {"database": True, "redis": True} assert status.backends == { "openai": "connected", "anthropic": "degraded", } def test_default_empty_dicts(self): """Test default empty dicts for optional fields""" status = HealthStatus(status="degraded", version="1.0.0", uptime_seconds=100.0) assert status.checks == {} assert status.backends == {} def test_invalid_status(self): """Test invalid status value raises error""" with pytest.raises(ValueError): HealthStatus(status="invalid", version="1.0.0", uptime_seconds=100.0) def test_valid_status_values(self): """Test all valid status values""" for status in ["healthy", "degraded", "unhealthy"]: hs = HealthStatus(status=status, version="1.0.0", uptime_seconds=100.0) assert hs.status == status # ============================================================================= # PaginatedResponse Tests # ============================================================================= class TestPaginatedResponse: """Tests for PaginatedResponse model""" def test_creation(self): """Test paginated response creation""" response = PaginatedResponse(items=[1, 2, 3], total=100, page=1, per_page=10, pages=10) assert response.items == [1, 2, 3] assert response.total == 100 assert response.page == 1 assert response.per_page == 10 assert response.pages == 10 def test_has_next_true(self): """Test has_next returns True when more pages exist""" response = PaginatedResponse(items=[], total=100, page=1, per_page=10, pages=10) assert response.has_next is True def test_has_next_false(self): """Test has_next returns False on last page""" response = PaginatedResponse(items=[], total=100, page=10, per_page=10, pages=10) assert response.has_next is False def test_has_prev_true(self): """Test has_prev returns True when not on first page""" response = PaginatedResponse(items=[], total=100, page=2, per_page=10, pages=10) assert response.has_prev is True def test_has_prev_false(self): """Test has_prev returns False on first page""" response = PaginatedResponse(items=[], total=100, page=1, per_page=10, pages=10) assert response.has_prev is False def test_any_item_type(self): """Test paginated response accepts any item type""" # String items response1 = PaginatedResponse(items=["a", "b", "c"], total=3, page=1, per_page=10, pages=1) assert response1.items == ["a", "b", "c"] # Dict items response2 = PaginatedResponse(items=[{"id": 1}, {"id": 2}], total=2, page=1, per_page=10, pages=1) assert len(response2.items) == 2 # Model items finding = Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", ) response3 = PaginatedResponse(items=[finding], total=1, page=1, per_page=10, pages=1) assert response3.items[0].title == "Test" # ============================================================================= # ReportConfig Tests # ============================================================================= class TestReportConfig: """Tests for ReportConfig model""" def test_default_creation(self): """Test default report config creation""" config = ReportConfig(title="Test Report", client_name="Client") assert config.title == "Test Report" assert config.client_name == "Client" assert config.format == "markdown" assert config.template == "technical" assert config.include_evidence is True assert config.include_remediation is True assert config.severity_filter is None def test_full_creation(self): """Test report config with all fields""" config = ReportConfig( title="Security Assessment", client_name="ACME Corp", format="pdf", template="executive", include_evidence=False, include_remediation=False, severity_filter=[Severity.HIGH, Severity.CRITICAL], ) assert config.format == "pdf" assert config.template == "executive" assert config.include_evidence is False assert config.include_remediation is False assert config.severity_filter == [Severity.HIGH, Severity.CRITICAL] def test_valid_formats(self): """Test all valid format values""" for fmt in ["markdown", "html", "pdf", "json"]: config = ReportConfig(title="Test", client_name="Client", format=fmt) assert config.format == fmt def test_invalid_format(self): """Test invalid format raises error""" with pytest.raises(ValueError): ReportConfig(title="Test", client_name="Client", format="docx") def test_valid_templates(self): """Test all valid template values""" for template in ["executive", "technical", "detailed"]: config = ReportConfig(title="Test", client_name="Client", template=template) assert config.template == template def test_invalid_template(self): """Test invalid template raises error""" with pytest.raises(ValueError): ReportConfig(title="Test", client_name="Client", template="invalid") def test_empty_title_raises_error(self): """Test empty title raises error""" with pytest.raises(ValueError): ReportConfig(title="", client_name="Client") def test_title_too_long(self): """Test title exceeding max length raises error""" with pytest.raises(ValueError): ReportConfig(title="A" * 201, client_name="Client") def test_empty_client_name_raises_error(self): """Test empty client_name raises error""" with pytest.raises(ValueError): ReportConfig(title="Test", client_name="") def test_client_name_too_long(self): """Test client_name exceeding max length raises error""" with pytest.raises(ValueError): ReportConfig(title="Test", client_name="A" * 201) def test_extra_forbidden(self): """Test extra fields are forbidden""" with pytest.raises(ValueError): ReportConfig(title="Test", client_name="Client", invalid_field="test") # ============================================================================= # Model Serialization Tests # ============================================================================= class TestModelSerialization: """Tests for model serialization/deserialization""" def test_finding_serialization(self): """Test finding can be serialized to dict""" finding = Finding( id="find-001", title="Test Finding", description="Test description", severity=Severity.HIGH, host="example.com", port=443, ) data = finding.model_dump() assert data["id"] == "find-001" assert data["title"] == "Test Finding" assert data["severity"] == "high" assert data["host"] == "example.com" def test_finding_json_serialization(self): """Test finding can be serialized to JSON""" finding = Finding( title="Test Finding", description="Test description", severity=Severity.MEDIUM, host="example.com", ) json_str = finding.model_dump_json() assert "Test Finding" in json_str assert "medium" in json_str def test_scan_result_serialization(self): """Test scan result serialization""" result = ScanResult( scan_id="scan-001", target="example.com", status=ScanStatus.COMPLETED, started_at=datetime.now(timezone.utc), ) data = result.model_dump() assert data["scan_id"] == "scan-001" assert data["target"] == "example.com" assert data["status"] == "completed" def test_nested_model_serialization(self): """Test nested models serialize correctly""" subdomain = SubdomainInfo(name="api.example.com", is_alive=True) recon = DomainRecon(domain="example.com", subdomains=[subdomain]) data = recon.model_dump() assert data["domain"] == "example.com" assert len(data["subdomains"]) == 1 assert data["subdomains"][0]["name"] == "api.example.com" # ============================================================================= # Edge Cases and Boundary Tests # ============================================================================= class TestEdgeCases: """Tests for edge cases and boundary conditions""" def test_scan_config_single_port(self): """Test scan config with single port""" config = ScanConfig(target="example.com", ports=[8080]) assert config.ports == [8080] def test_scan_config_all_ports(self): """Test scan config with many ports""" ports = list(range(1, 1001)) config = ScanConfig(target="example.com", ports=ports) assert len(config.ports) == 1000 def test_finding_cvss_boundary_values(self): """Test CVSS score at boundary values""" finding0 = Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", cvss_score=0.0, ) assert finding0.cvss_score == 0.0 finding10 = Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", cvss_score=10.0, ) assert finding10.cvss_score == 10.0 def test_empty_lists_default_factory(self): """Test that default factory creates new lists""" config1 = ScanConfig(target="example.com") config2 = ScanConfig(target="example.org") # Modify one list config1.ports.append(8080) # Other should be unchanged assert config2.ports == [80, 443] def test_finding_default_lists(self): """Test finding default lists are independent""" finding1 = Finding( title="Test1", description="Test", severity=Severity.LOW, host="example.com", ) finding2 = Finding( title="Test2", description="Test", severity=Severity.LOW, host="example.com", ) finding1.tags.append("tag1") assert "tag1" not in finding2.tags def test_unicode_in_prompt(self): """Test unicode characters in LLM prompt""" request = LLMRequest(prompt="Hello 世界 🌍 Привет") assert request.prompt == "Hello 世界 🌍 Привет" def test_unicode_in_finding(self): """Test unicode in finding fields""" finding = Finding( title="Vulnerability in 世界", description="Description: 测试", severity=Severity.INFO, host="例子.com", ) assert "世界" in finding.title assert "测试" in finding.description def test_datetime_timezone_handling(self): """Test datetime fields work correctly""" dt = datetime(2024, 1, 1, 12, 0, 0) result = ScanResult( scan_id="scan-001", target="example.com", status=ScanStatus.COMPLETED, started_at=dt, completed_at=dt, ) assert result.started_at == dt assert result.duration_seconds == 0.0 def test_very_long_description(self): """Test finding accepts very long description""" long_desc = "A" * 10000 finding = Finding( title="Test", description=long_desc, severity=Severity.LOW, host="example.com", ) assert finding.description == long_desc def test_many_cve_ids(self): """Test finding with many CVE IDs""" cves = [f"CVE-2023-{1000 + i:04d}" for i in range(100)] finding = Finding( title="Test", description="Test", severity=Severity.LOW, host="example.com", cve_ids=cves, ) assert len(finding.cve_ids) == 100 def test_special_chars_in_target_valid(self): """Test valid special characters in target""" # Dots and hyphens are valid config = ScanConfig(target="my-domain.example.com") assert config.target == "my-domain.example.com"
"""
Unit tests for core/models.py
Tests all Pydantic models, validators, and properties
"""
from datetime import datetime, timedelta, timezone
from typing import List, Optional
import pytest
from core.models import (
APIKeyConfig,
BackendType,
DomainRecon,
Finding,
HealthStatus,
LLMRequest,
LLMResponse,
PaginatedResponse,
ReportConfig,
ScanConfig,
ScanResult,
ScanStatus,
Severity,
SubdomainInfo,
TimestampedModel,
)
# =============================================================================
# Enum Tests
# =============================================================================
class TestSeverity:
"""Tests for Severity enum"""
def test_severity_values(self):
"""Test all severity enum values exist"""
assert Severity.CRITICAL == "critical"
assert Severity.HIGH == "high"
assert Severity.MEDIUM == "medium"
assert Severity.LOW == "low"
assert Severity.INFO == "info"
def test_severity_is_str_enum(self):
"""Test Severity is a string enum"""
assert isinstance(Severity.HIGH, str)
assert issubclass(Severity, str)
class TestScanStatus:
"""Tests for ScanStatus enum"""
def test_scan_status_values(self):
"""Test all scan status enum values exist"""
assert ScanStatus.PENDING == "pending"
assert ScanStatus.RUNNING == "running"
assert ScanStatus.COMPLETED == "completed"
assert ScanStatus.FAILED == "failed"
assert ScanStatus.CANCELLED == "cancelled"
class TestBackendType:
"""Tests for BackendType enum"""
def test_backend_type_values(self):
"""Test all backend type enum values exist"""
assert BackendType.DUCKDUCKGO == "duckduckgo"
assert BackendType.OPENROUTER == "openrouter"
assert BackendType.OPENAI == "openai"
assert BackendType.ANTHROPIC == "anthropic"
# =============================================================================
# TimestampedModel Tests
# =============================================================================
class TestTimestampedModel:
"""Tests for TimestampedModel base class"""
def test_default_creation(self):
"""Test model creation with default timestamps"""
before = datetime.now(timezone.utc)
model = TimestampedModel()
after = datetime.now(timezone.utc)
# Note: Model uses utcnow() internally which creates naive datetime
assert before <= model.created_at <= after
assert model.updated_at is None
def test_custom_timestamps(self):
"""Test model with custom timestamps"""
created = datetime(2024, 1, 1, 12, 0, 0)
updated = datetime(2024, 1, 2, 12, 0, 0)
model = TimestampedModel(created_at=created, updated_at=updated)
assert model.created_at == created
assert model.updated_at == updated

Xet Storage Details

Size:
44.7 kB
·
Xet hash:
5646bf95314317aa88994c531a991e3fd233927b1666dd68e1c72652e7156b3c

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