#!/usr/bin/env python3 """ Backup Test Script Creates test data and validates backup functionality """ import os import sys import tempfile import shutil import sqlite3 from pathlib import Path import subprocess def create_test_data(test_dir: Path) -> Path: """Create test directory structure with SQLite databases""" print(f"Creating test data in: {test_dir}") # Create directory structure (test_dir / "app1" / "data").mkdir(parents=True) (test_dir / "app2" / "logs").mkdir(parents=True) (test_dir / "shared" / "configs").mkdir(parents=True) (test_dir / "node_modules").mkdir(parents=True) # Should be blocked # Create regular files (test_dir / "app1" / "config.json").write_text('{"name": "app1"}') (test_dir / "app2" / "settings.yaml").write_text('debug: true') (test_dir / "shared" / "common.txt").write_text('shared data') (test_dir / "node_modules" / "package.json").write_text('{}') # Should be ignored # Create SQLite databases db1_path = test_dir / "app1" / "data" / "app1.db" db2_path = test_dir / "app2" / "app2.sqlite" # Create database 1 conn1 = sqlite3.connect(db1_path) conn1.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)") conn1.execute("INSERT INTO users (name) VALUES ('Alice'), ('Bob')") conn1.commit() conn1.close() # Create database 2 conn2 = sqlite3.connect(db2_path) conn2.execute("CREATE TABLE logs (id INTEGER PRIMARY KEY, message TEXT, timestamp TEXT)") conn2.execute("INSERT INTO logs (message, timestamp) VALUES ('Test log', '2024-01-01')") conn2.commit() conn2.close() print(f"Test data created:") print(f" - Directory structure: app1/, app2/, shared/, node_modules/") print(f" - SQLite databases: {db1_path}, {db2_path}") print(f" - Regular files: config.json, settings.yaml, common.txt") return test_dir def run_backup_test(): """Run a complete backup test""" print("=== Backup Test Starting ===") with tempfile.TemporaryDirectory() as temp_dir: temp_path = Path(temp_dir) # Create test directories source_dir = temp_path / "source" work_dir = temp_path / "work" backup_dir = temp_path / "backups" source_dir.mkdir() work_dir.mkdir() backup_dir.mkdir() # Create test data create_test_data(source_dir) # Run backup script backup_script = Path(__file__).parent / "backup.py" if not backup_script.exists(): print(f"ERROR: Backup script not found at {backup_script}") return False print(f"\nRunning backup script...") cmd = [ sys.executable, str(backup_script), str(source_dir), "--work-dir", str(work_dir), "--backup-dir", str(backup_dir), "--log-level", "INFO" ] try: result = subprocess.run(cmd, capture_output=True, text=True) print(f"Backup script exit code: {result.returncode}") if result.stdout: print("STDOUT:") print(result.stdout) if result.stderr: print("STDERR:") print(result.stderr) if result.returncode != 0: print("ERROR: Backup script failed") return False # Validate results return validate_backup_results(source_dir, work_dir, backup_dir) except Exception as e: print(f"ERROR: Failed to run backup script: {e}") return False def validate_backup_results(source_dir: Path, work_dir: Path, backup_dir: Path) -> bool: """Validate backup results""" print("\n=== Validating Backup Results ===") success = True # Check if archive was created archives = list(backup_dir.glob("backup_*.tar.gz")) if not archives: print("ERROR: No backup archive found") return False archive = archives[0] print(f"✓ Backup archive created: {archive.name}") # Check work directory contents expected_files = [ "app1/config.json", "app1/data/app1.db", "app2/settings.yaml", "app2/app2.sqlite", "shared/common.txt" ] for expected_file in expected_files: work_file = work_dir / expected_file if work_file.exists(): print(f"✓ Found expected file: {expected_file}") else: print(f"✗ Missing expected file: {expected_file}") success = False # Check that blocklisted directory was excluded node_modules = work_dir / "node_modules" if node_modules.exists(): print("✗ Blocklisted directory 'node_modules' was not excluded") success = False else: print("✓ Blocklisted directory 'node_modules' was correctly excluded") # Validate SQLite databases db_files = [ work_dir / "app1/data/app1.db", work_dir / "app2/app2.sqlite" ] for db_file in db_files: if db_file.exists(): try: conn = sqlite3.connect(db_file) # Try to query the database cursor = conn.cursor() if "app1.db" in str(db_file): cursor.execute("SELECT COUNT(*) FROM users") count = cursor.fetchone()[0] if count == 2: print(f"✓ SQLite database {db_file.name} has correct data") else: print(f"✗ SQLite database {db_file.name} has incorrect data count: {count}") success = False else: cursor.execute("SELECT COUNT(*) FROM logs") count = cursor.fetchone()[0] if count == 1: print(f"✓ SQLite database {db_file.name} has correct data") else: print(f"✗ SQLite database {db_file.name} has incorrect data count: {count}") success = False conn.close() except Exception as e: print(f"✗ Failed to validate SQLite database {db_file}: {e}") success = False else: print(f"✗ SQLite database not found: {db_file}") success = False return success def main(): """Main function""" print("Backup Test Script") print("=" * 50) success = run_backup_test() if success: print("\n🎉 All tests passed!") sys.exit(0) else: print("\n❌ Some tests failed!") sys.exit(1) if __name__ == '__main__': main()