-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker_test.py
More file actions
369 lines (310 loc) Β· 13.2 KB
/
Copy pathdocker_test.py
File metadata and controls
369 lines (310 loc) Β· 13.2 KB
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#!/usr/bin/env python3
"""
Docker testing script for the voting system
"""
import subprocess
import time
import requests
import sys
import json
class DockerTester:
def __init__(self):
self.base_url = "http://localhost:5000"
self.containers = ["voting-app-voting-app-1", "voting-app-db-1"]
def run_command(self, cmd, capture_output=True):
"""Run a shell command"""
try:
if capture_output:
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.returncode == 0, result.stdout, result.stderr
else:
result = subprocess.run(cmd, shell=True)
return result.returncode == 0, "", ""
except Exception as e:
return False, "", str(e)
def check_docker(self):
"""Check if Docker is available"""
print("π³ Checking Docker...")
success, stdout, stderr = self.run_command("docker --version")
if success:
print(f" β
Docker available: {stdout.strip()}")
else:
print(f" β Docker not available: {stderr}")
return False
success, stdout, stderr = self.run_command("docker-compose --version")
if success:
print(f" β
Docker Compose available: {stdout.strip()}")
return True
else:
print(f" β Docker Compose not available: {stderr}")
return False
def stop_existing_containers(self):
"""Stop any existing containers"""
print("\nπ Stopping existing containers...")
success, stdout, stderr = self.run_command("docker-compose down")
if success:
print(" β
Existing containers stopped")
else:
print(f" β οΈ Could not stop containers (might not be running): {stderr}")
def build_and_start(self):
"""Build and start the Docker containers"""
print("\nπ¨ Building and starting containers...")
# Build the application
print(" π¦ Building voting-app...")
success, stdout, stderr = self.run_command("docker-compose build voting-app")
if not success:
print(f" β Build failed: {stderr}")
return False
print(" β
Build completed")
# Start all services
print(" π Starting all services...")
success, stdout, stderr = self.run_command("docker-compose up -d")
if not success:
print(f" β Failed to start services: {stderr}")
return False
print(" β
Services started")
return True
def wait_for_services(self, timeout=120):
"""Wait for services to be healthy"""
print(f"\nβ³ Waiting for services to be ready (timeout: {timeout}s)...")
start_time = time.time()
db_ready = False
app_ready = False
while time.time() - start_time < timeout:
# Check database
if not db_ready:
success, stdout, stderr = self.run_command("docker-compose exec -T db pg_isready -U postgres")
if success:
print(" β
Database is ready")
db_ready = True
# Check application
if db_ready and not app_ready:
try:
response = requests.get(f"{self.base_url}/api/v1/health", timeout=5)
if response.status_code == 200:
print(" β
Application is ready")
app_ready = True
except:
pass
if db_ready and app_ready:
return True
print(" β³ Still waiting...")
time.sleep(5)
print(f" β Timeout waiting for services")
return False
def check_logs(self):
"""Check container logs for errors"""
print("\nπ Checking container logs...")
for container in ["voting-app", "db"]:
print(f"\n π Logs for {container}:")
success, stdout, stderr = self.run_command(f"docker-compose logs --tail=10 {container}")
if success:
lines = stdout.split('\n')[-10:] # Last 10 lines
for line in lines:
if line.strip():
print(f" {line}")
else:
print(f" β Could not get logs: {stderr}")
def setup_database(self):
"""Setup database with sample data"""
print("\nποΈ Setting up database...")
# Use the programmatic approach instead of interactive
success, stdout, stderr = self.run_command(
"docker-compose exec -T voting-app python -c \"from fix_database import run_all_setup; run_all_setup()\""
)
if success:
print(" β
Database setup completed")
return True
else:
print(f" β Database setup failed: {stderr}")
# Try individual steps
print(" π Trying individual setup steps...")
commands = [
"from fix_database import fix_database; fix_database()",
"from fix_database import create_sample_voting; create_sample_voting()",
"from fix_database import create_nase_firmy_sample; create_nase_firmy_sample()"
]
for i, cmd in enumerate(commands, 1):
print(f" Step {i}/3...")
success, stdout, stderr = self.run_command(
f'docker-compose exec -T voting-app python -c "{cmd}"'
)
if success:
print(f" β
Step {i} completed")
else:
print(f" β Step {i} failed: {stderr}")
if i == 1: # If fix_database fails, stop
return False
return True
def test_api_endpoints(self):
"""Test API endpoints"""
print("\nπ Testing API endpoints...")
endpoints = [
("/api/v1/health", "Health check"),
("/api/config", "Configuration"),
("/api/v1/templates", "Question templates"),
("/api/v1/voting", "Voting sessions (GET)"),
]
for endpoint, description in endpoints:
try:
response = requests.get(f"{self.base_url}{endpoint}", timeout=10)
if response.status_code == 200:
print(f" β
{description}: OK")
if endpoint == "/api/v1/templates":
data = response.json()
nase_firmy = any(t.get('name') == 'NaΕ‘e firmy' for t in data)
if nase_firmy:
print(f" β
'NaΕ‘e firmy' template found")
else:
print(f" β οΈ 'NaΕ‘e firmy' template missing")
else:
print(f" β {description}: {response.status_code}")
except Exception as e:
print(f" β {description}: {e}")
def test_frontend(self):
"""Test frontend pages"""
print("\nπ Testing frontend...")
pages = [
("/", "Admin interface"),
("/login", "Login page"),
]
for endpoint, description in pages:
try:
response = requests.get(f"{self.base_url}{endpoint}", timeout=10)
if response.status_code == 200:
print(f" β
{description}: OK")
# Check for modern UI elements
if endpoint == "/" and "Inter" in response.text:
print(f" β
Modern UI detected")
else:
print(f" β {description}: {response.status_code}")
except Exception as e:
print(f" β {description}: {e}")
def create_test_voting(self):
"""Create a test voting session via API"""
print("\nπ³οΈ Creating test voting session...")
payload = {
"name": "Docker Test Voting",
"description": "Test voting created via Docker API",
"questions": [
{
"text": "Rate the Docker setup",
"question_type": "rating",
"options": ["1", "2", "3", "4", "5"]
}
],
"teams": [
{"name": "Docker Team", "external_id": "docker_team"},
{"name": "Test Team", "external_id": "test_team"}
]
}
try:
response = requests.post(
f"{self.base_url}/api/v1/voting",
headers={"Content-Type": "application/json"},
json=payload,
timeout=10
)
if response.status_code == 201:
data = response.json()
voting_id = data['id']
print(f" β
Test voting created: {voting_id}")
print(f" π³οΈ Voting URL: {self.base_url}/hlasovani/{voting_id}")
print(f" π± QR Code: {self.base_url}/presentation/{voting_id}")
# Start the voting
start_response = requests.post(f"{self.base_url}/api/v1/voting/{voting_id}/start", timeout=10)
if start_response.status_code == 200:
print(f" β
Voting started successfully")
return voting_id
else:
print(f" β Could not start voting: {start_response.status_code}")
else:
print(f" β Could not create voting: {response.status_code} - {response.text}")
except Exception as e:
print(f" β Error creating voting: {e}")
return None
def show_access_info(self):
"""Show access information"""
print("\nπ Access Information:")
print("=" * 50)
print(f"π Admin Interface: {self.base_url}")
print(f"π API Health Check: {self.base_url}/api/v1/health")
print(f"π API Documentation: See API_DOCUMENTATION.md")
print(f"ποΈ Database Admin (pgAdmin): http://localhost:8080")
print(f" π§ Email: admin@example.com")
print(f" π Password: admin")
print("=" * 50)
def cleanup(self):
"""Cleanup containers"""
print("\nπ§Ή Cleanup options:")
print("1. Keep containers running")
print("2. Stop containers (keep data)")
print("3. Stop and remove everything (including data)")
choice = input("Choose (1-3): ").strip()
if choice == "2":
print("π Stopping containers...")
self.run_command("docker-compose down")
print("β
Containers stopped (data preserved)")
elif choice == "3":
print("ποΈ Removing everything...")
self.run_command("docker-compose down -v")
print("β
Everything removed")
else:
print("β
Containers left running")
def run_full_test(self):
"""Run the complete test suite"""
print("π§ͺ Docker Testing Suite for Voting System")
print("=" * 50)
# Check prerequisites
if not self.check_docker():
return False
# Stop existing containers
self.stop_existing_containers()
# Build and start
if not self.build_and_start():
return False
# Wait for services
if not self.wait_for_services():
self.check_logs()
return False
# Setup database
if not self.setup_database():
self.check_logs()
return False
# Test APIs
self.test_api_endpoints()
# Test frontend
self.test_frontend()
# Create test voting
voting_id = self.create_test_voting()
# Show access info
self.show_access_info()
# Test summary
print("\nπ Docker test completed!")
if voting_id:
print(f"β
Test voting created and ready: {voting_id}")
print("\nπ Next steps:")
print("1. Open the admin interface in your browser")
print("2. Test the modern UI and team selection")
print("3. Create 'NaΕ‘e firmy' voting sessions")
print("4. Test the QR code functionality")
return True
def main():
"""Main function"""
tester = DockerTester()
try:
success = tester.run_full_test()
if success:
print("\nπ All tests passed! Your Docker setup is working correctly.")
else:
print("\nπ₯ Some tests failed. Check the output above for details.")
# Cleanup
tester.cleanup()
except KeyboardInterrupt:
print("\n\nβ οΈ Test interrupted by user")
tester.cleanup()
except Exception as e:
print(f"\nπ₯ Unexpected error: {e}")
tester.cleanup()
if __name__ == "__main__":
main()