This repository was archived by the owner on Jul 19, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtest_task_execution.py
More file actions
166 lines (132 loc) Β· 4.88 KB
/
Copy pathtest_task_execution.py
File metadata and controls
166 lines (132 loc) Β· 4.88 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
#!/usr/bin/env python3
"""
Test actual task execution with a running Celery worker.
"""
import time
import sys
from pathlib import Path
# Add the app directory to the Python path
sys.path.insert(0, str(Path(__file__).parent))
from app.core.celery_app import celery_app
def test_task_execution():
"""Test executing tasks and waiting for results."""
print("π Testing Task Execution with Running Worker")
print("=" * 60)
# Test simple tasks that should complete quickly
test_tasks = [
{
'name': 'Health Check',
'task': 'app.tasks.maintenance.health_check',
'args': [],
'timeout': 30
},
{
'name': 'Generate Corpus Statistics',
'task': 'app.tasks.data_analysis.generate_corpus_statistics',
'args': [],
'timeout': 30
},
{
'name': 'Generate System Health Report',
'task': 'app.tasks.reports.generate_system_health_report',
'args': [],
'timeout': 30
}
]
results = []
for test_case in test_tasks:
print(f"\nπ Testing: {test_case['name']}")
print(f" Task: {test_case['task']}")
try:
# Send task
result = celery_app.send_task(
test_case['task'],
args=test_case['args']
)
print(f" Task ID: {result.task_id}")
print(f" Initial Status: {result.status}")
# Wait for completion with timeout
start_time = time.time()
timeout = test_case['timeout']
while time.time() - start_time < timeout:
status = result.status
print(f" Status: {status}", end='\r')
if status in ['SUCCESS', 'FAILURE', 'REVOKED']:
break
time.sleep(1)
final_status = result.status
print(f"\n Final Status: {final_status}")
if final_status == 'SUCCESS':
try:
task_result = result.get()
print(f" β
Result: {task_result}")
results.append(True)
except Exception as e:
print(f" β οΈ Result Error: {e}")
results.append(False)
elif final_status == 'FAILURE':
try:
error = result.traceback
print(f" β Error: {error}")
results.append(False)
except Exception as e:
print(f" β Failed to get error: {e}")
results.append(False)
else:
print(f" β±οΈ Timeout or pending: Status {final_status}")
results.append(False)
except Exception as e:
print(f" β Exception: {e}")
results.append(False)
# Summary
print("\n" + "=" * 60)
print("TASK EXECUTION SUMMARY")
print("=" * 60)
passed = sum(results)
total = len(results)
print(f"π Tasks completed successfully: {passed}/{total}")
if passed == total:
print("π All tasks executed successfully!")
return 0
else:
print(f"β οΈ {total - passed} task(s) failed or timed out.")
return 1
def check_worker_status():
"""Check if workers are running."""
print("π Checking Worker Status")
print("=" * 60)
try:
inspect = celery_app.control.inspect()
# Get active workers
stats = inspect.stats()
if stats:
print(f"β
Found {len(stats)} active worker(s):")
for worker_name, worker_stats in stats.items():
print(f" - {worker_name}")
else:
print("β No active workers found!")
print(" Start a worker with:")
print(" uv run celery -A app.core.celery_app worker --loglevel=info")
return False
# Get active tasks
active = inspect.active()
if active:
total_active = sum(len(worker_tasks) for worker_tasks in active.values())
print(f"π Active tasks: {total_active}")
else:
print("π No active tasks")
return True
except Exception as e:
print(f"β Error checking worker status: {e}")
return False
def main():
"""Run the task execution test."""
print(f"π
Timestamp: {time.strftime('%Y-%m-%d %H:%M:%S')}")
# Check worker status first
if not check_worker_status():
print("\nβ οΈ No workers available for testing.")
return 1
# Run task execution tests
return test_task_execution()
if __name__ == "__main__":
sys.exit(main())