# Copyright 2026 Element Creations Ltd # # SPDX-License-Identifier: AGPL-3.0-only """ Pytest tests for user prompts in the migration script. Tests for missing secrets and extra files handling. """ import asyncio import base64 import logging from io import StringIO import pytest from ..engine import MigrationEngine from ..inputs import InputProcessor def test_migration_with_missing_secrets_prompt( monkeypatch, tmp_path, synapse_config_with_signing_key, write_synapse_config ): """Test migration workflow that prompts for missing secrets with timeout.""" # Create Synapse configuration with missing secrets synapse_config = synapse_config_with_signing_key.copy() # Remove password to simulate missing secret del synapse_config["database"]["args"]["password"] # Remove other secrets to simulate missing secrets del synapse_config["macaroon_secret_key"] del synapse_config["registration_shared_secret"] # Write Synapse config synapse_config_file = write_synapse_config(synapse_config) # Load migration input - this should prompt for missing secrets input_processor = InputProcessor() input_processor.load_migration_input( config_path=str(synapse_config_file), name="synapse", ) ess_values = {} log_capture_string = StringIO() pretty_logger = logging.getLogger(test_migration_with_missing_secrets_prompt.__name__) pretty_logger.propagate = False pretty_logger.setLevel(logging.INFO) pretty_logger.addHandler(logging.StreamHandler(log_capture_string)) engine = MigrationEngine(input_processor, pretty_logger=pretty_logger) # Mock user input for missing secrets side_effect = (n for n in ("test_db_password", "test_macaroon", "test_registration")) monkeypatch.setattr("builtins.input", lambda _: next(side_effect)) # Test with async timeout to prevent hanging async def test_with_timeout(): nonlocal ess_values ess_values = engine.run_migration() # Run the async test with timeout try: asyncio.run(asyncio.wait_for(test_with_timeout(), timeout=10.0)) # Capture the output after the test runs output = log_capture_string.getvalue() # Verify that warnings about generated secrets are present assert "SECRETS REQUIRED FOR MIGRATION" in output assert "Synapse database password" in output assert "Synapse macaroon secret" in output assert "✅ All required SYNAPSE secrets have been provided" in output # Verify that secrets were handled synapse_config_result = ess_values["synapse"] # Check that serverName is present at the top level of ess_values (camelCase for Helm values) assert "serverName" in ess_values assert ess_values["serverName"] == "test.example.com" # Check that credential schema was used for required secrets # Only macaroon has init_if_missing_from_source_cfg=False in this test assert "macaroon" in synapse_config_result # Verify that Secrets were generated assert len(engine.secrets) > 0 for secret in engine.secrets: assert "synapse.postgres.password" in secret.data assert base64.b64decode(secret.data["synapse.postgres.password"]) == b"test_db_password" assert "synapse.macaroon" in secret.data assert base64.b64decode(secret.data["synapse.macaroon"]) == b"test_macaroon" # registration shared secret is accepted to be generated by init secrets assert "synapse.registrationSharedSecret" not in secret.data except TimeoutError: pytest.fail("Test timed out - prompt may be hanging") except Exception as e: # If the test fails, it should be a meaningful failure # not a timeout or input issue if "TimeoutError" in str(e) or "asyncio" in str(e): pytest.fail(f"Async test failed: {e}") else: # Re-raise the original exception raise finally: log_capture_string.close() def test_migration_with_unknown_workers_prompt( monkeypatch, tmp_path, synapse_config_with_signing_key, synapse_config_with_instance_map, write_synapse_config, ): """Test migration workflow that prompts for missing secrets with timeout.""" # Write Synapse config synapse_config_file = write_synapse_config(synapse_config_with_signing_key | synapse_config_with_instance_map) # Load migration input - this should prompt for missing secrets input_processor = InputProcessor() input_processor.load_migration_input( config_path=str(synapse_config_file), name="synapse", ) ess_values = {} log_capture_string = StringIO() pretty_logger = logging.getLogger(test_migration_with_unknown_workers_prompt.__name__) pretty_logger.propagate = False pretty_logger.setLevel(logging.INFO) pretty_logger.addHandler(logging.StreamHandler(log_capture_string)) engine = MigrationEngine(input_processor, pretty_logger=pretty_logger) # Mock user input for workers side_effect = (n for n in ("8")) monkeypatch.setattr("builtins.input", lambda _: next(side_effect)) # Test with async timeout to prevent hanging async def test_with_timeout(): nonlocal ess_values ess_values = engine.run_migration() # Run the async test with timeout try: asyncio.run(asyncio.wait_for(test_with_timeout(), timeout=10.0)) # Capture the output after the test runs output = log_capture_string.getvalue() assert " No worker type found for instance funny-name" in output # Verify that secrets were handled synapse_config_result = ess_values["synapse"] assert "workers" in synapse_config_result assert len(synapse_config_result["workers"]) == 2 assert "event-creator" in synapse_config_result["workers"] assert "synchrotron" in synapse_config_result["workers"] assert synapse_config_result["workers"]["synchrotron"]["replicas"] == 2 except TimeoutError: pytest.fail("Test timed out - prompt may be hanging") except Exception as e: # If the test fails, it should be a meaningful failure # not a timeout or input issue if "TimeoutError" in str(e) or "asyncio" in str(e): pytest.fail(f"Async test failed: {e}") else: # Re-raise the original exception raise finally: log_capture_string.close() def test_migration_with_missing_extra_files_prompt( monkeypatch, tmp_path, synapse_config_with_signing_key, synapse_config_with_email_templates, write_synapse_config, ): """Test migration workflow that prompts for missing secrets with timeout.""" # Write Synapse config synapse_config_file = write_synapse_config(synapse_config_with_signing_key | synapse_config_with_email_templates) # Load migration input - this should prompt for missing secrets input_processor = InputProcessor() input_processor.load_migration_input( config_path=str(synapse_config_file), name="synapse", ) ess_values = {} (tmp_path / "email_templates").move(tmp_path / "moved") log_capture_string = StringIO() pretty_logger = logging.getLogger(test_migration_with_missing_extra_files_prompt.__name__) pretty_logger.propagate = False pretty_logger.setLevel(logging.INFO) pretty_logger.addHandler(logging.StreamHandler(log_capture_string)) engine = MigrationEngine(input_processor, pretty_logger=pretty_logger) # Mock user input for extra files discovery side_effect = (n for n in ("3", str(tmp_path / "moved"))) monkeypatch.setattr("builtins.input", lambda _: next(side_effect)) # Test with async timeout to prevent hanging async def test_with_timeout(): nonlocal ess_values ess_values = engine.run_migration() # Run the async test with timeout try: asyncio.run(asyncio.wait_for(test_with_timeout(), timeout=10.0)) # Capture the output after the test runs output = log_capture_string.getvalue() # Verify that warnings about generated secrets are present assert "📁 EXTRA FILES DISCOVERY" in output assert "The following extra files were referenced in your configuration" in output assert " ⚠️ Skipping missing files..." not in output assert f" ✅ Found 2 matching files in {(str(tmp_path / 'moved'))}" in output # Verify that extra files were handled synapse_config = ess_values["synapse"] assert len(synapse_config["extraVolumeMounts"]) == 2 except TimeoutError: pytest.fail("Test timed out - prompt may be hanging") except Exception as e: # If the test fails, it should be a meaningful failure # not a timeout or input issue if "TimeoutError" in str(e) or "asyncio" in str(e): pytest.fail(f"Async test failed: {e}") else: # Re-raise the original exception raise finally: log_capture_string.close()