-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtest_rabbitmq_integration.py
More file actions
265 lines (232 loc) · 9.3 KB
/
test_rabbitmq_integration.py
File metadata and controls
265 lines (232 loc) · 9.3 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
#!/usr/bin/env python3
"""
Test script for RabbitMQ integration in Sentinel platform.
This script tests the asynchronous message broker architecture.
"""
import asyncio
import json
import time
import pika
import httpx
from typing import Dict, Any
# Configuration
API_GATEWAY_URL = "http://localhost:8000"
RABBITMQ_URL = "amqp://guest:guest@localhost:5672/"
TASK_QUEUE = "sentinel_task_queue"
RESULT_QUEUE = "sentinel_result_queue"
class RabbitMQIntegrationTest:
def __init__(self):
self.connection = None
self.channel = None
self.results = []
def connect_rabbitmq(self):
"""Connect to RabbitMQ"""
try:
self.connection = pika.BlockingConnection(pika.URLParameters(RABBITMQ_URL))
self.channel = self.connection.channel()
self.channel.queue_declare(queue=TASK_QUEUE, durable=True)
self.channel.queue_declare(queue=RESULT_QUEUE, durable=True)
print("✅ Connected to RabbitMQ")
return True
except Exception as e:
print(f"❌ Failed to connect to RabbitMQ: {e}")
return False
def publish_test_task(self, task_data: Dict[str, Any]):
"""Publish a test task to RabbitMQ"""
try:
message = json.dumps(task_data)
self.channel.basic_publish(
exchange='',
routing_key=TASK_QUEUE,
body=message,
properties=pika.BasicProperties(
delivery_mode=2, # make message persistent
))
print(f"📤 Published task: {task_data.get('task', {}).get('task_id')}")
return True
except Exception as e:
print(f"❌ Failed to publish task: {e}")
return False
def check_queue_depth(self):
"""Check the number of messages in the queue"""
try:
method = self.channel.queue_declare(queue=TASK_QUEUE, durable=True, passive=True)
return method.method.message_count
except Exception as e:
print(f"❌ Failed to check queue depth: {e}")
return -1
async def test_http_endpoint(self):
"""Test the HTTP endpoint to ensure it still works"""
async with httpx.AsyncClient() as client:
try:
# Test health endpoint
response = await client.get(f"{API_GATEWAY_URL}/health")
if response.status_code == 200:
print("✅ API Gateway health check passed")
else:
print(f"❌ API Gateway health check failed: {response.status_code}")
# Test creating a specification
spec_data = {
"name": "RabbitMQ Test API",
"version": "1.0.0",
"openapi": "3.0.0",
"paths": {
"/test": {
"get": {
"summary": "Test endpoint",
"responses": {
"200": {
"description": "Success",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"message": {"type": "string"}
}
}
}
}
}
}
}
}
}
}
response = await client.post(
f"{API_GATEWAY_URL}/specs",
json=spec_data
)
if response.status_code in [200, 201]:
spec_id = response.json().get("id")
print(f"✅ Created test specification: {spec_id}")
return spec_id
else:
print(f"❌ Failed to create specification: {response.status_code}")
return None
except Exception as e:
print(f"❌ HTTP test failed: {e}")
return None
async def test_message_broker_flow(self, spec_id: str):
"""Test the complete message broker flow"""
# Create test task
test_task = {
"task": {
"task_id": f"rabbitmq-test-{int(time.time())}",
"agent_type": "functional-positive",
"spec_id": spec_id,
"parameters": { # Add required parameters field
"max_test_cases": 5
},
"target_environment": "test"
},
"api_spec": {
"openapi": "3.0.0",
"paths": {
"/test": {
"get": {
"summary": "Test endpoint",
"responses": {
"200": {
"description": "Success"
}
}
}
}
}
}
}
# Check initial queue depth
initial_depth = self.check_queue_depth()
print(f"📊 Initial queue depth: {initial_depth}")
# Publish task
if self.publish_test_task(test_task):
# Wait a bit for processing
await asyncio.sleep(2)
# Check queue depth after publishing
after_publish_depth = self.check_queue_depth()
print(f"📊 Queue depth after publish: {after_publish_depth}")
# Wait for processing
print("⏳ Waiting for task processing...")
await asyncio.sleep(5)
# Check final queue depth
final_depth = self.check_queue_depth()
print(f"📊 Final queue depth: {final_depth}")
if final_depth < after_publish_depth:
print("✅ Task was consumed from the queue")
return True
else:
print("⚠️ Task may not have been processed")
return False
return False
def cleanup(self):
"""Clean up connections"""
if self.connection:
self.connection.close()
print("🧹 Closed RabbitMQ connection")
async def main():
print("🚀 Starting RabbitMQ Integration Test")
print("=" * 50)
tester = RabbitMQIntegrationTest()
# Step 1: Connect to RabbitMQ
if not tester.connect_rabbitmq():
print("❌ Cannot proceed without RabbitMQ connection")
return
# Step 2: Test HTTP endpoints
print("\n📝 Testing HTTP endpoints...")
spec_id = await tester.test_http_endpoint()
if not spec_id:
print("⚠️ Continuing with mock spec_id")
spec_id = "test-spec-123"
# Step 3: Test message broker flow
print("\n📬 Testing message broker flow...")
success = await tester.test_message_broker_flow(spec_id)
# Step 4: Test multiple tasks
print("\n📦 Testing multiple task publishing...")
for i in range(3):
test_task = {
"task": {
"task_id": f"batch-test-{i}-{int(time.time())}",
"agent_type": "data-mocking",
"spec_id": spec_id,
"parameters": { # Add required parameters field
"count": 3
},
"target_environment": "test"
},
"api_spec": {
"openapi": "3.0.0",
"paths": {
f"/test{i}": {
"get": {
"summary": f"Test endpoint {i}",
"responses": {
"200": {
"description": "Success"
}
}
}
}
}
}
}
tester.publish_test_task(test_task)
await asyncio.sleep(0.5)
print("⏳ Waiting for batch processing...")
await asyncio.sleep(5)
final_queue_depth = tester.check_queue_depth()
print(f"\n📊 Final queue depth after batch: {final_queue_depth}")
# Cleanup
tester.cleanup()
print("\n" + "=" * 50)
if success:
print("✅ RabbitMQ integration test completed successfully!")
else:
print("⚠️ RabbitMQ integration test completed with warnings")
print("\n📋 Test Summary:")
print("- RabbitMQ connection: ✅")
print(f"- HTTP endpoints: {'✅' if spec_id else '⚠️'}")
print(f"- Message broker flow: {'✅' if success else '⚠️'}")
print(f"- Final queue status: {final_queue_depth} messages remaining")
if __name__ == "__main__":
asyncio.run(main())