from __future__ import annotations from dataclasses import dataclass from types import SimpleNamespace import pytest from fastapi.testclient import TestClient from app.database import Base, engine from app.main import app from app.models.prediction import ConfidenceLevel, PredictionLabel, PredictionResponse from app.models.virustotal import VirusTotalResponse FEATURE_COUNT = 2381 FEATURES = [0.0] * FEATURE_COUNT SHA256 = "a" * 64 class FakeMLService: model_loaded = True feature_count = FEATURE_COUNT model = object() def predict(self, features, threshold=None, sha256=None): if len(features) != self.feature_count: raise ValueError(f"Expected {self.feature_count} features, got {len(features)}") used_threshold = 0.5 if threshold is None else threshold return PredictionResponse( prediction=PredictionLabel.MALICIOUS, probability=0.91, confidence=ConfidenceLevel.HIGH, threshold_used=used_threshold, sha256=sha256, inference_time_ms=1.2, ) def get_model_info(self): return { "loaded": True, "feature_count": self.feature_count, "default_threshold": 0.5, "model_type": "FakeModel", } class FakeSHAPService: initialized = True def initialize(self, model): self.initialized = True def get_feature_importance(self, features, model=None, top_k=10): return [] def explain(self, features): return [] class FakeGeminiService: initialized = False model = None def initialize(self): self.initialized = False async def explain_prediction(self, prediction, features=None): return { "risk_explanation": "Deterministic test explanation.", "severity_level": "High", "key_indicators": ["test signal"], "analyst_summary": "Smoke test summary.", "mitigation_steps": ["isolate sample"], } class FakeURLService: model_loaded = True _dl_available = False def predict(self, url, threshold=0.5): return { "url": url, "prediction": "Malicious", "malicious_score": 0.84, "confidence": "84.0%", "confidence_level": "High", "threshold_used": threshold, "base_model_scores": {"XGBoost": 0.8}, "top_signals": {"url_length": 0.4}, "inference_time_ms": 3.4, } def get_model_info(self): return { "model_type": "Fake URL HyperModel", "base_models": ["XGBoost"], "meta_learner": "XGBoost", "scaler_features": 54, "meta_features": 10, "dl_available": self._dl_available, "feature_categories": ["lexical"], } class FakeVirusTotalService: initialized = True next_result: VirusTotalResponse | None = None async def lookup_hash(self, sha256): if self.next_result is not None: return self.next_result return VirusTotalResponse( sha256=sha256, found=True, detection_ratio=0.25, total_engines=20, malicious_count=5, ) class FakeFeedbackService: def __init__(self): self.malware_total = 0 self.url_total = 0 def log_malware_feedback(self, **kwargs): self.malware_total += 1 return { "success": True, "reward": 1, "message": "Agreement with VirusTotal logged", "total_feedback_count": self.malware_total, } def log_url_feedback(self, **kwargs): self.url_total += 1 return { "success": True, "reward": 1, "message": "Feedback recorded", "total_feedback_count": self.url_total, } def maybe_auto_update(self, model_type): return None def get_stats(self): return { "malware_total": self.malware_total, "malware_agree": self.malware_total, "malware_disagree": 0, "malware_agreement_rate": 100.0 if self.malware_total else 0.0, "url_total": self.url_total, "url_correct": self.url_total, "url_incorrect": 0, "url_accuracy_rate": 100.0 if self.url_total else 0.0, "recent_malware": [], "recent_url": [], "model_updates": [], } @dataclass class Services: ml: FakeMLService shap: FakeSHAPService gemini: FakeGeminiService url: FakeURLService virustotal: FakeVirusTotalService feedback: FakeFeedbackService @pytest.fixture def features(): return list(FEATURES) @pytest.fixture def sha256(): return SHA256 @pytest.fixture def services(monkeypatch): fakes = Services( ml=FakeMLService(), shap=FakeSHAPService(), gemini=FakeGeminiService(), url=FakeURLService(), virustotal=FakeVirusTotalService(), feedback=FakeFeedbackService(), ) from app import dependencies from app.routers import chat, feedback, predict, upload, url, virustotal from app import main fake_analyst = SimpleNamespace( id=1, email="analyst@example.com", display_name="Analyst", role="admin", tier="enterprise", is_active=True, created_at=None, ) app.dependency_overrides[predict.get_ml_service] = lambda: fakes.ml app.dependency_overrides[predict.get_gemini_service] = lambda: fakes.gemini app.dependency_overrides[virustotal.get_ml_service] = lambda: fakes.ml app.dependency_overrides[virustotal.get_virustotal_service] = lambda: fakes.virustotal app.dependency_overrides[dependencies.require_analyst] = lambda: fake_analyst app.dependency_overrides[dependencies.require_admin] = lambda: fake_analyst monkeypatch.setattr(main, "get_ml_service", lambda: fakes.ml) monkeypatch.setattr(main, "get_gemini_service", lambda: fakes.gemini) monkeypatch.setattr(main, "get_virustotal_service", lambda: fakes.virustotal) monkeypatch.setattr(predict, "get_shap_service", lambda: fakes.shap) monkeypatch.setattr(chat, "get_gemini_service", lambda: fakes.gemini) monkeypatch.setattr(upload, "get_ml_service", lambda: fakes.ml) monkeypatch.setattr(upload, "get_shap_service", lambda: fakes.shap) monkeypatch.setattr(upload, "get_gemini_service", lambda: fakes.gemini) monkeypatch.setattr(upload, "LIEF_AVAILABLE", True) monkeypatch.setattr(url, "get_url_service", lambda: fakes.url) monkeypatch.setattr(feedback, "get_feedback_service", lambda: fakes.feedback) monkeypatch.setattr(virustotal, "get_feedback_service", lambda: fakes.feedback) yield fakes app.dependency_overrides.clear() @pytest.fixture def client(services, monkeypatch): from app.config import settings monkeypatch.setattr(settings, "anonymous_file_scan_limit", 10_000) monkeypatch.setattr(settings, "anonymous_url_scan_limit", 10_000) monkeypatch.setattr(settings, "free_file_scan_limit", 10_000) monkeypatch.setattr(settings, "free_url_scan_limit", 10_000) Base.metadata.create_all(bind=engine) return TestClient(app)