import pytest from unittest.mock import MagicMock, patch import os import sys # Ensure project root is in python path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) @pytest.fixture(scope="session", autouse=True) def mock_external_services(): """Mock database setup, background threads, and other external dependencies globally.""" # Mock the database connection wrappers mock_conn = MagicMock() mock_cur = MagicMock() mock_conn.cursor.return_value = mock_cur mock_cur.fetchone.return_value = (1, "Test Key", ["detect", "admin"]) mock_cur.fetchall.return_value = [] with patch('utils.auth.init_db'), \ patch('scripts.setup_timescaledb.initialize_schema'), \ patch('src.utils.telemetry.start_metrics_collection_thread'), \ patch('src.routes.training.start_feedback_watcher'), \ patch('src.middleware.api_auth.get_db_connection', return_value=mock_conn), \ patch('utils.auth._get_conn', return_value=mock_conn), \ patch('src.utils.telemetry.get_db_connection', return_value=mock_conn), \ patch('src.utils.telemetry.log_detection_metrics'), \ patch('src.utils.telemetry.log_demorph_metrics'): yield @pytest.fixture def app(): """Create a configured Flask app instance for testing.""" os.environ['MORPHGUARD_SECRET_KEY'] = 'test-secret-key' os.environ['FLASK_ENV'] = 'testing' os.environ['CTM_ENABLED'] = 'false' # Disable CTM in unit tests to avoid extra dependencies # Mock MorphGuardAPI instantiation with patch('app.MorphGuardAPI') as mock_api_class: mock_api = MagicMock() # Set up default returns mock_api.detect_morph.return_value = { 'is_morphed': True, 'confidence': 0.88, 'processing_time': 0.25 } mock_api.demorph_image.return_value = { 'success': True, 'processing_time': 0.45 } mock_api_class.return_value = mock_api # Mock DeepfakeDetectorAPI instantiation with patch('src.deepfake.deepfake_detector.DeepfakeDetectorAPI') as mock_df_class: mock_df = MagicMock() mock_df.detect.return_value = { 'is_deepfake': True, 'deepfake_score': 0.95, 'artifacts': ['some_artifact'] } mock_df_class.return_value = mock_df from app import create_app flask_app = create_app() flask_app.config['TESTING'] = True # Make the mocked api instances accessible on the app object for assertions flask_app.mg_api = mock_api flask_app.deepfake_detector = mock_df yield flask_app @pytest.fixture def client(app): """A Flask test client.""" return app.test_client()