Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /tests /test_batch3_final.py
| """ | |
| Final corrected tests using real API signatures: | |
| - validate_finding() is ASYNC | |
| - prioritize_findings() is SYNC | |
| - calculate_risk_score() is SYNC | |
| - ToolRegistry uses LangChain BaseTool | |
| """ | |
| import asyncio | |
| from datetime import datetime | |
| from typing import List | |
| from unittest.mock import AsyncMock, MagicMock, patch | |
| import pytest | |
| # ============================================================================= | |
| # FalsePositiveEngine with real dataclasses | |
| # ============================================================================= | |
| try: | |
| from risk_engine.false_positive_engine import ( | |
| CVSSData, | |
| FalsePositiveEngine, | |
| Finding, | |
| FindingStatus, | |
| RiskFactors, | |
| ValidationResult, | |
| VulnerabilityType, | |
| ) | |
| HAS_FP_ENGINE = True | |
| except ImportError as e: | |
| HAS_FP_ENGINE = False | |
| print(f"FP Engine import error: {e}") | |
| def make_finding( | |
| id="f1", | |
| title="Test Finding", | |
| description="A test finding", | |
| severity="high", | |
| vuln_type=VulnerabilityType.INJECTION, | |
| cvss_score=8.5, | |
| confidence=0.8, | |
| **kwargs, | |
| ): | |
| """Create a real Finding dataclass instance.""" | |
| if not HAS_FP_ENGINE: | |
| return None | |
| rf = RiskFactors( | |
| epss_score=0.5, | |
| business_impact=0.7, | |
| exploitability=0.6, | |
| asset_criticality=0.8, | |
| cvss_data=CVSSData( | |
| base_score=cvss_score, | |
| temporal_score=cvss_score, | |
| environmental_score=cvss_score, | |
| ), | |
| ) | |
| return Finding( | |
| id=id, | |
| title=title, | |
| description=description, | |
| severity=severity, | |
| vulnerability_type=vuln_type, | |
| risk_factors=rf, | |
| confidence=confidence, | |
| target=kwargs.get("target", "http://test.com"), | |
| source=kwargs.get("source", "test_scanner"), | |
| scanner=kwargs.get("scanner", "nmap"), | |
| raw_evidence=kwargs.get("raw_evidence", {"payload": "test"}), | |
| ) | |
| class TestFalsePositiveEngineInit: | |
| """Test engine instantiation.""" | |
| def test_default_init(self): | |
| engine = FalsePositiveEngine() | |
| assert engine is not None | |
| def test_init_with_database_path(self): | |
| engine = FalsePositiveEngine(fp_database_path="/tmp/fp_test.db") # nosec B108) | |
| assert engine is not None | |
| def test_init_llm_voting_disabled(self): | |
| engine = FalsePositiveEngine(enable_llm_voting=False) | |
| assert engine is not None | |
| def test_init_with_epss_endpoint(self): | |
| engine = FalsePositiveEngine(epss_api_endpoint="https://api.first.org/data/v1/epss") | |
| assert engine is not None | |
| class TestValidateFinding: | |
| """Test finding validation - ASYNC, returns ValidationResult.""" | |
| def setup_method(self): | |
| self.engine = FalsePositiveEngine(enable_llm_voting=False) | |
| async def test_validate_sqli(self): | |
| f = make_finding( | |
| id="sqli_1", | |
| title="SQL Injection", | |
| description="SQL injection in login form", | |
| vuln_type=VulnerabilityType.SQL_INJECTION, | |
| severity="critical", | |
| cvss_score=9.5, | |
| ) | |
| result = await self.engine.validate_finding(f) | |
| assert isinstance(result, ValidationResult) | |
| assert hasattr(result, "is_false_positive") | |
| async def test_validate_xss(self): | |
| f = make_finding( | |
| id="xss_1", | |
| title="XSS", | |
| description="Reflected XSS in search", | |
| vuln_type=VulnerabilityType.XSS, | |
| severity="medium", | |
| cvss_score=6.1, | |
| ) | |
| result = await self.engine.validate_finding(f) | |
| assert isinstance(result, ValidationResult) | |
| async def test_validate_rce(self): | |
| f = make_finding( | |
| id="rce_1", | |
| title="RCE", | |
| description="Remote code execution", | |
| vuln_type=VulnerabilityType.RCE, | |
| severity="critical", | |
| cvss_score=10.0, | |
| ) | |
| result = await self.engine.validate_finding(f) | |
| assert isinstance(result, ValidationResult) | |
| async def test_validation_result_has_required_fields(self): | |
| f = make_finding(id="test_1") | |
| result = await self.engine.validate_finding(f) | |
| assert result.finding == f | |
| assert isinstance(result.is_false_positive, bool) | |
| assert isinstance(result.confidence, float) | |
| assert isinstance(result.risk_score, float) | |
| assert isinstance(result.priority, int) | |
| assert isinstance(result.reasoning, str) | |
| async def test_validate_weak_finding(self): | |
| f = make_finding( | |
| id="weak_1", | |
| title="Weak Finding", | |
| description="Low confidence finding", | |
| confidence=0.2, | |
| severity="info", | |
| cvss_score=2.0, | |
| ) | |
| result = await self.engine.validate_finding(f) | |
| assert isinstance(result, ValidationResult) | |
| async def test_validate_all_severity_levels(self): | |
| for sev in ["info", "low", "medium", "high", "critical"]: | |
| f = make_finding(id=f"sev_{sev}", severity=sev) | |
| result = await self.engine.validate_finding(f) | |
| assert isinstance(result, ValidationResult) | |
| async def test_validate_all_vuln_types(self): | |
| for vt in VulnerabilityType: | |
| f = make_finding(id=f"vt_{vt.name}", vuln_type=vt) | |
| result = await self.engine.validate_finding(f) | |
| assert isinstance(result, ValidationResult) | |
| class TestCalculateRiskScore: | |
| """Test risk score calculation - SYNC, takes RiskFactors, returns float.""" | |
| def setup_method(self): | |
| self.engine = FalsePositiveEngine(enable_llm_voting=False) | |
| def test_risk_score_returns_number(self): | |
| rf = RiskFactors( | |
| epss_score=0.8, | |
| business_impact=0.9, | |
| exploitability=0.7, | |
| asset_criticality=0.8, | |
| cvss_data=CVSSData(base_score=8.5, temporal_score=8.5, environmental_score=8.5), | |
| ) | |
| score = self.engine.calculate_risk_score(rf) | |
| assert isinstance(score, (int, float)) | |
| def test_risk_score_in_range(self): | |
| rf = RiskFactors(cvss_data=CVSSData(base_score=5.0, temporal_score=5.0, environmental_score=5.0)) | |
| score = self.engine.calculate_risk_score(rf) | |
| assert 0.0 <= score <= 100.0 # CVSS range | |
| def test_critical_scores_higher_than_low(self): | |
| low_rf = RiskFactors( | |
| epss_score=0.1, | |
| business_impact=0.1, | |
| exploitability=0.1, | |
| asset_criticality=0.1, | |
| cvss_data=CVSSData(base_score=2.0, temporal_score=2.0, environmental_score=2.0), | |
| ) | |
| crit_rf = RiskFactors( | |
| epss_score=0.9, | |
| business_impact=0.9, | |
| exploitability=0.9, | |
| asset_criticality=0.9, | |
| cvss_data=CVSSData(base_score=10.0, temporal_score=10.0, environmental_score=10.0), | |
| ) | |
| low_score = self.engine.calculate_risk_score(low_rf) | |
| crit_score = self.engine.calculate_risk_score(crit_rf) | |
| assert crit_score > low_score | |
| class TestPrioritizeFindings: | |
| """Test finding prioritization - SYNC, returns List.""" | |
| def setup_method(self): | |
| self.engine = FalsePositiveEngine(enable_llm_voting=False) | |
| def test_empty_list(self): | |
| result = self.engine.prioritize_findings([]) | |
| assert result == [] | |
| def test_single_finding(self): | |
| findings = [make_finding(id="f1")] | |
| result = self.engine.prioritize_findings(findings) | |
| assert len(result) == 1 | |
| def test_preserves_all_findings(self): | |
| findings = [ | |
| make_finding(id="f1", vuln_type=VulnerabilityType.SQL_INJECTION), | |
| make_finding(id="f2", vuln_type=VulnerabilityType.XSS), | |
| make_finding(id="f3", vuln_type=VulnerabilityType.RCE), | |
| make_finding(id="f4", vuln_type=VulnerabilityType.BROKEN_ACCESS_CONTROL), | |
| ] | |
| result = self.engine.prioritize_findings(findings) | |
| assert len(result) == 4 | |
| def test_critical_before_low(self): | |
| findings = [ | |
| make_finding(id="low", severity="low", cvss_score=2.0), | |
| make_finding(id="crit", severity="critical", cvss_score=10.0), | |
| make_finding(id="med", severity="medium", cvss_score=5.0), | |
| ] | |
| result = self.engine.prioritize_findings(findings) | |
| # First result should be critical | |
| assert result[0].id == "crit" | |
| def test_returns_list_of_findings(self): | |
| findings = [make_finding(id=f"f{i}") for i in range(5)] | |
| result = self.engine.prioritize_findings(findings) | |
| assert isinstance(result, list) | |
| assert all(isinstance(f, Finding) for f in result) | |
| def test_large_batch(self): | |
| findings = [make_finding(id=f"f{i}", target=f"http://host{i}.com") for i in range(50)] | |
| result = self.engine.prioritize_findings(findings) | |
| assert len(result) == 50 | |
| class TestLearnFromFeedback: | |
| """Test feedback learning - SYNC method.""" | |
| def setup_method(self): | |
| self.engine = FalsePositiveEngine(enable_llm_voting=False) | |
| def test_feedback_true_positive(self): | |
| self.engine.learn_from_feedback(finding_id="sqli_http://test.com", is_fp=False, user="test_user") | |
| def test_feedback_false_positive(self): | |
| self.engine.learn_from_feedback(finding_id="xss_http://test.com", is_fp=True, user="test_user") | |
| def test_multiple_feedback_entries(self): | |
| for i in range(5): | |
| self.engine.learn_from_feedback(finding_id=f"vuln_{i}", is_fp=(i % 2 == 0), user="test_user") | |
| class TestCheckEPSS: | |
| """Test EPSS checking - ASYNC with mocked network.""" | |
| def setup_method(self): | |
| self.engine = FalsePositiveEngine( | |
| epss_api_endpoint="https://api.first.org/data/v1/epss", | |
| enable_llm_voting=False, | |
| ) | |
| async def test_epss_returns_float(self): | |
| with patch("aiohttp.ClientSession") as mock_session: | |
| mock_resp = AsyncMock() | |
| mock_resp.json = AsyncMock(return_value={"data": [{"cve": "CVE-2024-1234", "epss": "0.9712"}]}) | |
| mock_resp.__aenter__ = AsyncMock(return_value=mock_resp) | |
| mock_resp.__aexit__ = AsyncMock(return_value=False) | |
| mock_session.return_value.__aenter__ = AsyncMock(return_value=mock_session.return_value) | |
| mock_session.return_value.__aexit__ = AsyncMock(return_value=False) | |
| mock_session.return_value.get = MagicMock(return_value=mock_resp) | |
| score = await self.engine.check_epss("CVE-2024-1234") | |
| assert isinstance(score, (float, int)) or score is None | |
| class TestMultiLLMVoting: | |
| """Test LLM voting - ASYNC.""" | |
| def setup_method(self): | |
| self.engine = FalsePositiveEngine(enable_llm_voting=True) | |
| # Register mock LLMs | |
| for i in range(3): | |
| mock_llm = AsyncMock() | |
| mock_llm.complete = AsyncMock(return_value='{"is_fp": false, "confidence": 0.9}') | |
| self.engine.register_llm(f"llm_{i}", mock_llm) | |
| async def test_voting_returns_result(self): | |
| f = make_finding(id="vote_test") | |
| result = await self.engine.multi_llm_voting(f) | |
| assert result is not None | |
| assert isinstance(result, tuple) | |
| assert len(result) == 2 | |
| # ============================================================================= | |
| # Memory and Cache Tests | |
| # ============================================================================= | |
| try: | |
| from core.cache import CacheStats, MemoryCache, MultiTierCache, SQLiteCache | |
| HAS_CACHE = True | |
| except ImportError: | |
| HAS_CACHE = False | |
| class TestCacheStats: | |
| """CacheStats is a dataclass with attributes.""" | |
| def test_initial_state(self): | |
| s = CacheStats() | |
| assert s.hits == 0 | |
| assert s.misses == 0 | |
| def test_increment_hits(self): | |
| s = CacheStats() | |
| s.hits += 5 | |
| assert s.hits == 5 | |
| def test_increment_misses(self): | |
| s = CacheStats() | |
| s.misses += 3 | |
| assert s.misses == 3 | |
| class TestMemoryCache: | |
| """MemoryCache has async methods.""" | |
| async def test_set_and_get(self): | |
| c = MemoryCache(max_size=20, default_ttl=60) | |
| await c.set("k", "hello") | |
| result = await c.get("k") | |
| assert result == "hello" | |
| async def test_get_missing(self): | |
| c = MemoryCache(max_size=20, default_ttl=60) | |
| result = await c.get("nonexistent") | |
| assert result is None | |
| async def test_delete(self): | |
| c = MemoryCache(max_size=20, default_ttl=60) | |
| await c.set("del", "v") | |
| await c.delete("del") | |
| assert await c.get("del") is None | |
| async def test_clear(self): | |
| c = MemoryCache(max_size=20, default_ttl=60) | |
| await c.set("a", 1) | |
| await c.set("b", 2) | |
| await c.clear() | |
| assert await c.get("a") is None | |
| assert await c.get("b") is None | |
| # ============================================================================= | |
| # Run tests and check coverage | |
| # ============================================================================= | |
| if __name__ == "__main__": | |
| pytest.main([__file__, "-v", "--tb=short"]) | |
Xet Storage Details
- Size:
- 14.2 kB
- Xet hash:
- 750ea4d339ab0bb33465c47283120651a80265434c0ef54fcfa65460a62722ec
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.