1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
|
#!/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()
|