~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test: add critical path stability tests
LearningCircuitcf80c7282162
diff --git a/tests/api_tests/test_api_contracts.py b/tests/api_tests/test_api_contracts.pynew file mode 100644index 0000000000..2e1abc99d9--- /dev/null+++ b/tests/api_tests/test_api_contracts.py@@ -0,0 +1,184 @@+#!/usr/bin/env python3+"""+Test API response contracts.++These tests verify that API responses have the expected structure.+Breaking these contracts will break client integrations.+"""++import pytest+++class TestResearchStatusValues:+ """+ Verify that research status values are consistent.++ Clients depend on these exact string values.+ """++ def test_research_status_enum_values(self):+ """+ Verify ResearchStatus enum has expected values.++ Clients check for these exact string values in responses.+ Changing them will break client code.+ """+ from src.local_deep_research.database.models.research import (+ ResearchStatus,+ )++ # These are the status values clients depend on+ expected_values = {+ "pending",+ "in_progress",+ "completed",+ "failed",+ "cancelled",+ "suspended",+ }++ actual_values = {status.value for status in ResearchStatus}++ # Check no expected values were removed+ missing = expected_values - actual_values+ assert not missing, (+ f"ResearchStatus is missing expected values: {missing}\n"+ "Clients depend on these status values.\n"+ "Removing them will break client integrations."+ )++ def test_research_mode_enum_values(self):+ """+ Verify ResearchMode enum has expected values.++ Clients use these values when starting research.+ """+ from src.local_deep_research.database.models.research import (+ ResearchMode,+ )++ # These are the mode values clients depend on+ expected_values = {+ "quick",+ "detailed",+ }++ actual_values = {mode.value for mode in ResearchMode}++ missing = expected_values - actual_values+ assert not missing, (+ f"ResearchMode is missing expected values: {missing}\n"+ "Clients depend on these mode values."+ )+++class TestResponseStructures:+ """+ Verify that models have expected columns for API responses.++ These are the fields that clients depend on.+ """++ def test_research_has_required_columns(self):+ """+ Verify Research model has required columns for API responses.++ These columns are serialized in API responses.+ """+ from src.local_deep_research.database.models.research import Research++ required_columns = {+ "id",+ "query",+ "status",+ "mode",+ "created_at",+ }++ actual_columns = set(Research.__table__.columns.keys())++ missing = required_columns - actual_columns+ assert not missing, (+ f"Research model is missing required columns: {missing}\n"+ "These columns are expected in API responses."+ )++ def test_user_settings_has_required_columns(self):+ """+ Verify UserSettings model has required columns for API responses.+ """+ from src.local_deep_research.database.models import UserSettings++ required_columns = {"id", "key", "value", "category"}++ actual_columns = set(UserSettings.__table__.columns.keys())++ missing = required_columns - actual_columns+ assert not missing, (+ f"UserSettings model is missing required columns: {missing}\n"+ "These columns are expected in settings API responses."+ )+++class TestAPIEndpointPaths:+ """+ Document critical API endpoint paths.++ These tests don't hit the actual endpoints, but document+ the expected paths that clients depend on.+ """++ def test_critical_endpoint_paths_documented(self):+ """+ Document the critical API endpoint paths.++ Changing these paths will break client integrations.+ """+ # These are the critical endpoint paths that should not change+ critical_paths = [+ # Auth+ "/auth/login",+ "/auth/logout",+ "/auth/csrf-token",+ # Research API+ "/api/start_research",+ "/api/research/<research_id>",+ "/api/research/<research_id>/status",+ "/api/history",+ "/api/report/<research_id>",+ # Settings+ "/settings/api",+ "/settings/api/<path:key>",+ # API v1+ "/api/v1/health",+ "/api/v1/quick_summary",+ "/api/v1/generate_report",+ ]++ # This test documents the expected paths.+ # Actual endpoint testing is done in integration tests.+ assert len(critical_paths) > 0, "Critical paths should be documented"+++class TestErrorResponseFormat:+ """+ Verify error responses have consistent format.+ """++ def test_error_response_keys(self):+ """+ Document expected error response format.++ Error responses should have "error" or "message" key.+ """+ # Expected error response structures:+ # {"error": "Error message"}+ # {"status": "error", "message": "Error message"}++ # This is documentation - actual format testing is in integration tests+ expected_error_keys = ["error", "message", "status"]+ assert len(expected_error_keys) > 0, "Error keys should be documented"+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/tests/database/test_backwards_compatibility.py b/tests/database/test_backwards_compatibility.pynew file mode 100644index 0000000000..229085cd24--- /dev/null+++ b/tests/database/test_backwards_compatibility.py@@ -0,0 +1,239 @@+#!/usr/bin/env python3+"""+Test backwards compatibility for encrypted databases.++This test ensures that databases created with previous versions can still+be opened with the current version. This prevents breaking changes like+salt modifications from going undetected.++The key tests are:+1. TestSaltStability - Fast tests that verify encryption constants haven't changed+2. TestBackwardsCompatibility - Slow test that actually installs previous PyPI version++The salt stability tests run in CI and catch 99% of breaking changes.+The full backwards compatibility test can be run manually with:+ pytest tests/database/test_backwards_compatibility.py -m slow --run-slow+"""++import os+import subprocess+import sys+import tempfile+from pathlib import Path++import pytest+++# Script to create a database using the installed package+CREATE_DB_SCRIPT = """+import sys+import tempfile+from pathlib import Path++# Set up paths+db_dir = Path(sys.argv[1])+username = sys.argv[2]+password = sys.argv[3]++# Patch the data directory before importing+import local_deep_research.config.paths as paths_module+original_get_data_directory = paths_module.get_data_directory+paths_module.get_data_directory = lambda: db_dir++from local_deep_research.database.encrypted_db import DatabaseManager++# Create a fresh manager with patched path+manager = DatabaseManager()+manager.data_dir = db_dir / "encrypted_databases"+manager.data_dir.mkdir(parents=True, exist_ok=True)++# Create the database+engine = manager.create_user_database(username, password)++# Add some test data+session = manager.get_session(username)+from local_deep_research.database.models import UserSettings+setting = UserSettings(+ key="test.backwards_compat",+ value={"version": "previous", "test": True},+ category="test",+)+session.add(setting)+session.commit()+session.close()++manager.close_user_database(username)+print("Database created successfully")+"""+++class TestBackwardsCompatibility:+ """Test that current version can open databases from previous versions."""++ @pytest.fixture+ def temp_dir(self):+ """Create a temporary directory for test databases."""+ with tempfile.TemporaryDirectory() as tmpdir:+ yield Path(tmpdir)++ def get_previous_version(self) -> str:+ """Get the previous version number from PyPI."""+ result = subprocess.run(+ [+ sys.executable,+ "-m",+ "pip",+ "index",+ "versions",+ "local-deep-research",+ ],+ capture_output=True,+ text=True,+ )++ if result.returncode != 0:+ # Fallback: try to get from pip show+ result = subprocess.run(+ [sys.executable, "-m", "pip", "show", "local-deep-research"],+ capture_output=True,+ text=True,+ )+ # Can't determine previous version+ pytest.skip("Could not determine previous version from PyPI")++ # Parse versions from output+ # Output format: "local-deep-research (1.3.21)\nAvailable versions: 1.3.21, 1.3.20, ..."+ for line in result.stdout.split("\n"):+ if "Available versions:" in line:+ versions = line.split(":")[1].strip().split(", ")+ if len(versions) >= 2:+ return versions[1] # Second version is the previous one++ pytest.skip("Could not find previous version")++ @pytest.mark.slow+ @pytest.mark.skipif(+ os.environ.get("RUN_SLOW_TESTS") != "true",+ reason="Slow test - set RUN_SLOW_TESTS=true to run",+ )+ def test_open_database_from_previous_version(self, temp_dir, monkeypatch):+ """+ Test that we can open a database created with the previous PyPI version.++ This test:+ 1. Installs the previous version in an isolated venv+ 2. Creates a database using that version+ 3. Verifies the current version can open it and read data+ """+ # Get previous version+ try:+ previous_version = self.get_previous_version()+ except Exception as e:+ pytest.skip(f"Could not get previous version: {e}")++ # Create isolated venv for previous version+ venv_dir = temp_dir / "prev_venv"+ db_dir = temp_dir / "databases"+ db_dir.mkdir()++ # Create venv+ result = subprocess.run(+ [sys.executable, "-m", "venv", str(venv_dir)],+ capture_output=True,+ text=True,+ )+ if result.returncode != 0:+ pytest.skip(f"Could not create venv: {result.stderr}")++ # Get venv python+ if sys.platform == "win32":+ venv_python = venv_dir / "Scripts" / "python.exe"+ else:+ venv_python = venv_dir / "bin" / "python"++ # Install previous version (with timeout)+ result = subprocess.run(+ [+ str(venv_python),+ "-m",+ "pip",+ "install",+ f"local-deep-research=={previous_version}",+ "--quiet",+ ],+ capture_output=True,+ text=True,+ timeout=300, # 5 minute timeout+ )+ if result.returncode != 0:+ pytest.skip(f"Could not install previous version: {result.stderr}")++ # Create database with previous version+ username = "compat_test_user"+ password = "CompatTestPass123!"++ script_file = temp_dir / "create_db.py"+ script_file.write_text(CREATE_DB_SCRIPT)++ result = subprocess.run(+ [+ str(venv_python),+ str(script_file),+ str(db_dir),+ username,+ password,+ ],+ capture_output=True,+ text=True,+ timeout=60,+ )+ if result.returncode != 0:+ pytest.fail(+ f"Could not create database with previous version: {result.stderr}"+ )++ # Now test opening with current version+ monkeypatch.setattr(+ "src.local_deep_research.database.encrypted_db.get_data_directory",+ lambda: db_dir,+ )++ from src.local_deep_research.database.encrypted_db import (+ DatabaseManager,+ )+ from src.local_deep_research.database.models import UserSettings++ manager = DatabaseManager()+ manager.data_dir = db_dir / "encrypted_databases"++ # Try to open the database+ engine = manager.open_user_database(username, password)+ assert engine is not None, (+ f"Failed to open database created with version {previous_version}. "+ "This likely means a breaking change was introduced (e.g., salt change)."+ )++ # Verify we can read the data+ session = manager.get_session(username)+ setting = (+ session.query(UserSettings)+ .filter_by(key="test.backwards_compat")+ .first()+ )++ assert setting is not None, (+ "Could not read data from previous version database"+ )+ assert setting.value["version"] == "previous"+ assert setting.value["test"] is True++ session.close()+ manager.close_user_database(username)+++# Note: Salt stability tests have been moved to test_encryption_constants.py+# This file now only contains the slow PyPI backwards compatibility test.+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/tests/database/test_encryption_constants.py b/tests/database/test_encryption_constants.pynew file mode 100644index 0000000000..37bdb9fb0c--- /dev/null+++ b/tests/database/test_encryption_constants.py@@ -0,0 +1,178 @@+#!/usr/bin/env python3+"""+Test that encryption constants never change.++These tests protect against breaking changes to encryption parameters.+If ANY of these tests fail, it means ALL existing encrypted databases+will become unreadable. REVERT THE CHANGE IMMEDIATELY.++This test file exists because a "documentation only" commit changed+the PBKDF2 salt and broke all existing user databases.+"""++import hashlib+from hashlib import pbkdf2_hmac++import pytest+++class TestEncryptionConstants:+ """+ Verify that encryption constants haven't changed.++ CRITICAL: These values are used to derive encryption keys.+ Changing ANY of them will make existing databases unreadable.+ """++ def test_salt_value_is_stable(self):+ """+ Ensure the PBKDF2 salt value hasn't changed.++ WARNING: Changing this salt will break ALL existing user databases!+ If this test fails, you MUST revert the salt change.+ """+ from src.local_deep_research.database.sqlcipher_utils import (+ PBKDF2_PLACEHOLDER_SALT,+ )++ expected_salt = b"no salt"++ assert PBKDF2_PLACEHOLDER_SALT == expected_salt, (+ f"CRITICAL: PBKDF2 salt has changed!\n"+ f"Expected: {expected_salt!r}\n"+ f"Actual: {PBKDF2_PLACEHOLDER_SALT!r}\n\n"+ "This will break ALL existing encrypted databases!\n"+ "Users will be unable to log in.\n"+ "REVERT THIS CHANGE IMMEDIATELY."+ )++ def test_kdf_iterations_stable(self):+ """+ Ensure KDF iterations haven't changed.++ Changing this will make existing databases unreadable.+ """+ from src.local_deep_research.database.sqlcipher_utils import (+ DEFAULT_KDF_ITERATIONS,+ )++ expected_iterations = 256000++ assert DEFAULT_KDF_ITERATIONS == expected_iterations, (+ f"CRITICAL: KDF iterations changed!\n"+ f"Expected: {expected_iterations}\n"+ f"Actual: {DEFAULT_KDF_ITERATIONS}\n\n"+ "This will break ALL existing encrypted databases!\n"+ "REVERT THIS CHANGE IMMEDIATELY."+ )++ def test_hmac_algorithm_stable(self):+ """+ Ensure HMAC algorithm hasn't changed.++ Changing this will make existing databases unreadable.+ """+ from src.local_deep_research.database.sqlcipher_utils import (+ DEFAULT_HMAC_ALGORITHM,+ )++ expected_algorithm = "HMAC_SHA512"++ assert DEFAULT_HMAC_ALGORITHM == expected_algorithm, (+ f"CRITICAL: HMAC algorithm changed!\n"+ f"Expected: {expected_algorithm}\n"+ f"Actual: {DEFAULT_HMAC_ALGORITHM}\n\n"+ "This will break ALL existing encrypted databases!\n"+ "REVERT THIS CHANGE IMMEDIATELY."+ )++ def test_page_size_stable(self):+ """+ Ensure cipher page size hasn't changed.++ Changing this will make existing databases unreadable.+ """+ from src.local_deep_research.database.sqlcipher_utils import (+ DEFAULT_PAGE_SIZE,+ )++ expected_page_size = 16384 # 16KB++ assert DEFAULT_PAGE_SIZE == expected_page_size, (+ f"CRITICAL: Page size changed!\n"+ f"Expected: {expected_page_size}\n"+ f"Actual: {DEFAULT_PAGE_SIZE}\n\n"+ "This will break ALL existing encrypted databases!\n"+ "REVERT THIS CHANGE IMMEDIATELY."+ )++ def test_kdf_algorithm_stable(self):+ """+ Ensure KDF algorithm hasn't changed.++ Changing this will make existing databases unreadable.+ """+ from src.local_deep_research.database.sqlcipher_utils import (+ DEFAULT_KDF_ALGORITHM,+ )++ expected_algorithm = "PBKDF2_HMAC_SHA512"++ assert DEFAULT_KDF_ALGORITHM == expected_algorithm, (+ f"CRITICAL: KDF algorithm changed!\n"+ f"Expected: {expected_algorithm}\n"+ f"Actual: {DEFAULT_KDF_ALGORITHM}\n\n"+ "This will break ALL existing encrypted databases!\n"+ "REVERT THIS CHANGE IMMEDIATELY."+ )++ def test_key_derivation_produces_expected_output(self):+ """+ Verify the key derivation function produces the expected output.++ This test uses a known password and verifies the derived key matches+ the expected hash. This catches ANY change to the key derivation:+ - Salt changes+ - Iteration count changes+ - Algorithm changes+ - Any other parameter changes++ If this test fails, existing databases WILL NOT be openable.+ """+ from src.local_deep_research.database.sqlcipher_utils import (+ PBKDF2_PLACEHOLDER_SALT,+ DEFAULT_KDF_ITERATIONS,+ )++ # Use a known test password+ test_password = "test_password_for_key_derivation_check"++ # Derive the key the same way the production code does+ derived_key = pbkdf2_hmac(+ "sha512",+ test_password.encode(),+ PBKDF2_PLACEHOLDER_SALT,+ DEFAULT_KDF_ITERATIONS,+ )++ # This is the expected hash of the derived key+ # Generated with: hashlib.sha256(derived_key).hexdigest()+ # If this changes, ALL existing databases will break!+ expected_key_hash = (+ "cfac783084917231b28210859f7722be29b54120161f43709363c07cfc6c63ed"+ )++ actual_key_hash = hashlib.sha256(derived_key).hexdigest()++ assert actual_key_hash == expected_key_hash, (+ f"CRITICAL: Key derivation output has changed!\n"+ f"Expected hash: {expected_key_hash}\n"+ f"Actual hash: {actual_key_hash}\n\n"+ "This means the encryption key for the same password is now different.\n"+ "ALL existing user databases will be unreadable!\n"+ "REVERT WHATEVER CHANGE CAUSED THIS IMMEDIATELY."+ )+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/tests/database/test_schema_stability.py b/tests/database/test_schema_stability.pynew file mode 100644index 0000000000..628f437bdb--- /dev/null+++ b/tests/database/test_schema_stability.py@@ -0,0 +1,216 @@+#!/usr/bin/env python3+"""+Test that database schema (table names) never changes unexpectedly.++Renaming or removing tables will cause data loss for existing users.+These tests catch accidental schema changes before they're deployed.+"""++import pytest+++# Expected table names - DO NOT REMOVE ANY+# Adding new tables is fine, but removing/renaming breaks existing databases+EXPECTED_TABLES = {+ # Auth (in auth.db, not user dbs)+ "users",+ # Settings+ "api_keys",+ "settings",+ "user_settings",+ # Cache+ "cache",+ "search_cache",+ # Queue+ "queue_status",+ "task_metadata",+ # Research+ "research",+ "research_history",+ "research_resources",+ "research_strategies",+ "research_tasks",+ "search_queries",+ "search_results",+ "queued_researches",+ "user_active_researches",+ # Reports+ "reports",+ "report_sections",+ # Library+ "collections",+ "collection_folders",+ "collection_folder_files",+ "documents",+ "document_blobs",+ "document_chunks",+ "document_collections",+ "download_queue",+ "library_statistics",+ "rag_document_status",+ "rag_indices",+ "source_types",+ "upload_batches",+ # Download tracking+ "download_tracker",+ "download_duplicates",+ "download_attempts",+ # Metrics+ "token_usage",+ "model_usage",+ "research_ratings",+ "search_calls",+ # News+ "news_cards",+ "news_interests",+ "news_subscriptions",+ "news_user_preferences",+ "news_user_ratings",+ "subscription_folders",+ "user_news_search_history",+ # File integrity+ "file_integrity_records",+ "file_verification_failures",+ # Providers+ "provider_models",+ # Rate limiting+ "rate_limit_attempts",+ "rate_limit_estimates",+ # Logs+ "app_logs",+ "journals",+ # Benchmark+ "benchmark_configs",+ "benchmark_progress",+ "benchmark_results",+ "benchmark_runs",+}+++class TestSchemaStability:+ """+ Verify that database table names haven't changed.++ Renaming or removing tables will cause existing user databases+ to lose data or fail to open properly.+ """++ def test_no_tables_removed(self):+ """+ Ensure no expected tables have been removed.++ Removing a table definition will cause data loss when users+ upgrade, as SQLAlchemy won't know how to access that data.+ """+ from src.local_deep_research.database.models import Base++ # Get all actual table names from the models+ actual_tables = set(Base.metadata.tables.keys())++ # Check that all expected tables still exist+ missing_tables = EXPECTED_TABLES - actual_tables++ assert not missing_tables, (+ f"CRITICAL: Database tables have been removed!\n"+ f"Missing tables: {missing_tables}\n\n"+ "Removing tables will cause data loss for existing users.\n"+ "If you intentionally removed these tables, you need a migration plan.\n"+ "Otherwise, REVERT THIS CHANGE."+ )++ def test_no_tables_renamed(self):+ """+ Detect if tables might have been renamed.++ If new tables appear and expected tables are missing,+ it's likely a rename which will cause data loss.+ """+ from src.local_deep_research.database.models import Base++ actual_tables = set(Base.metadata.tables.keys())+ missing_tables = EXPECTED_TABLES - actual_tables++ if missing_tables:+ # Check if there are new tables that might be renames+ new_tables = actual_tables - EXPECTED_TABLES++ if new_tables:+ pytest.fail(+ f"Possible table rename detected!\n"+ f"Missing: {missing_tables}\n"+ f"New: {new_tables}\n\n"+ "If you renamed tables, existing data will be lost.\n"+ "You need a migration to copy data from old to new tables."+ )++ def test_new_tables_are_documented(self):+ """+ Ensure any new tables are added to EXPECTED_TABLES.++ This is a reminder to update this test when adding new tables.+ New tables should be added to EXPECTED_TABLES to track them.+ """+ from src.local_deep_research.database.models import Base++ actual_tables = set(Base.metadata.tables.keys())+ new_tables = actual_tables - EXPECTED_TABLES++ # These are okay - just a reminder to update the test+ if new_tables:+ pytest.fail(+ f"New tables detected that aren't in EXPECTED_TABLES:\n"+ f"{new_tables}\n\n"+ "Please add these to EXPECTED_TABLES in this test file.\n"+ "This ensures they'll be protected from accidental removal."+ )+++class TestCriticalColumns:+ """+ Verify that critical columns in key tables haven't been removed.++ These are columns that store important user data.+ """++ def test_user_settings_has_required_columns(self):+ """Verify UserSettings table has all required columns."""+ from src.local_deep_research.database.models import UserSettings++ required_columns = {"id", "key", "value", "category"}+ actual_columns = set(UserSettings.__table__.columns.keys())++ missing = required_columns - actual_columns+ assert not missing, (+ f"UserSettings is missing required columns: {missing}\n"+ "This will break user settings storage."+ )++ def test_research_has_required_columns(self):+ """Verify Research table has all required columns."""+ from src.local_deep_research.database.models.research import Research++ required_columns = {"id", "query", "status", "mode", "created_at"}+ actual_columns = set(Research.__table__.columns.keys())++ missing = required_columns - actual_columns+ assert not missing, (+ f"Research is missing required columns: {missing}\n"+ "This will break research history."+ )++ def test_api_keys_has_required_columns(self):+ """Verify APIKey table has all required columns."""+ from src.local_deep_research.database.models import APIKey++ required_columns = {"id", "provider", "key", "is_active"}+ actual_columns = set(APIKey.__table__.columns.keys())++ missing = required_columns - actual_columns+ assert not missing, (+ f"APIKey is missing required columns: {missing}\n"+ "This will break API key storage."+ )+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])diff --git a/tests/security/test_session_constants.py b/tests/security/test_session_constants.pynew file mode 100644index 0000000000..24761456e3--- /dev/null+++ b/tests/security/test_session_constants.py@@ -0,0 +1,113 @@+#!/usr/bin/env python3+"""+Test that session security constants don't change unexpectedly.++These tests ensure session timeouts and security settings remain consistent.+Changing these values affects user experience and security.+"""++from datetime import timedelta++import pytest+++class TestSessionConstants:+ """+ Verify session timeout and security constants.++ These values affect how long users stay logged in and+ the security properties of their sessions.+ """++ def test_session_timeout_is_2_hours(self):+ """+ Verify the default session timeout is 2 hours.++ This is the timeout for users who don't check "remember me".+ Changing this affects user experience.+ """+ from src.local_deep_research.web.auth.session_manager import (+ SessionManager,+ )++ manager = SessionManager()+ expected = timedelta(hours=2)++ assert manager.session_timeout == expected, (+ f"Session timeout changed!\n"+ f"Expected: {expected}\n"+ f"Actual: {manager.session_timeout}\n\n"+ "This affects how long users stay logged in.\n"+ "If intentional, update this test."+ )++ def test_remember_me_timeout_is_30_days(self):+ """+ Verify the "remember me" session timeout is 30 days.++ This is the timeout for users who check "remember me".+ Changing this affects user experience.+ """+ from src.local_deep_research.web.auth.session_manager import (+ SessionManager,+ )++ manager = SessionManager()+ expected = timedelta(days=30)++ assert manager.remember_me_timeout == expected, (+ f"Remember me timeout changed!\n"+ f"Expected: {expected}\n"+ f"Actual: {manager.remember_me_timeout}\n\n"+ "This affects how long 'remember me' sessions last.\n"+ "If intentional, update this test."+ )++ def test_flask_session_lifetime_matches_session_timeout(self):+ """+ Verify Flask's PERMANENT_SESSION_LIFETIME matches session_timeout.++ These should be in sync to avoid confusing behavior.+ """+ # Import the value directly from app_factory configuration+ # This is the value in seconds+ expected_seconds = 7200 # 2 hours++ # We can't easily test the Flask config without creating an app,+ # so we just verify the expected value is documented here.+ # The actual config is set in app_factory.py line 221.+ assert expected_seconds == 2 * 60 * 60, (+ "PERMANENT_SESSION_LIFETIME should be 2 hours (7200 seconds)"+ )+++class TestSessionSecurity:+ """+ Verify session security settings.++ These settings protect against various attacks.+ """++ def test_session_cookie_settings_documented(self):+ """+ Document expected session cookie security settings.++ These are set in app_factory.py and should not be weakened.+ """+ # Expected settings (from app_factory.py):+ expected_settings = {+ "SESSION_COOKIE_HTTPONLY": True, # Prevents JavaScript access+ "SESSION_COOKIE_SAMESITE": "Lax", # CSRF protection+ # SESSION_COOKIE_SECURE is conditional on HTTPS+ }++ # This test documents the expected values.+ # The actual testing of Flask config would require app context.+ for setting, expected_value in expected_settings.items():+ assert expected_value is not None, (+ f"{setting} should be configured for security"+ )+++if __name__ == "__main__":+ pytest.main([__file__, "-v"])